OXYGENHUB

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

672 of 1753 lines run, 49 of 265 functions · run #543 on main · run missed

1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod mcp;
7
mod target;
8
mod ui;
9
10
use anyhow::{bail, Context, Result};
11
use clap::{Parser, Subcommand};
12
use client::Client;
13
use hub_api::{
14
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
15
};
16
use std::time::Duration;
17
use target::{Choice, Config, Target};
18
19
#[derive(Parser)]
20
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
21
struct Cli {
22
    /// The repository, when not inside an Oxygen checkout
23
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
24
    repo: Option<String>,
25
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
26
    #[arg(long, global = true, value_name = "URL")]
27
    hub: Option<String>,
28
    /// Which of the checkout's remotes to use (default: origin, or the only one)
29
    #[arg(long, global = true)]
30
    remote: Option<String>,
31
    /// Machine-readable output: the API's JSON, unchanged
32
    #[arg(long, global = true)]
33
    json: bool,
34
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
35
    #[arg(long, global = true)]
36
    plain: bool,
37
    #[command(subcommand)]
38
    cmd: Cmd,
39
}
40
41
#[derive(Subcommand)]
42
enum Cmd {
43
    /// Sign in to a hub, or show who you are signed in as
44
    Auth {
45
        #[command(subcommand)]
46
        cmd: AuthCmd,
47
    },
48
    /// The repository
49
    Repo {
50
        #[command(subcommand)]
51
        cmd: RepoCmd,
52
    },
53
    /// Issues
54
    Issue {
55
        #[command(subcommand)]
56
        cmd: IssueCmd,
57
    },
58
    /// Proposals (pull requests)
59
    Proposal {
60
        #[command(subcommand)]
61
        cmd: ProposalCmd,
62
    },
63
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
64
    Coverage {
65
        #[command(subcommand)]
66
        cmd: CoverageCmd,
67
    },
68
    /// OxygenFlow runs
69
    Run {
70
        #[command(subcommand)]
71
        cmd: RunCmd,
72
    },
73
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
74
    Report {
75
        #[command(subcommand)]
76
        cmd: ReportCmd,
77
    },
78
    /// Releases
79
    Release {
80
        #[command(subcommand)]
81
        cmd: ReleaseCmd,
82
    },
83
    /// Tags: list, create, withdraw
84
    Tag {
85
        #[command(subcommand)]
86
        cmd: TagCmd,
87
    },
88
    /// The repository's labels
89
    Label {
90
        #[command(subcommand)]
91
        cmd: LabelCmd,
92
    },
93
    /// Milestones: list, create, edit, close
94
    Milestone {
95
        #[command(subcommand)]
96
        cmd: MilestoneCmd,
97
    },
98
    /// Project boards of the repository's owner (or --owner): list,
99
    /// create, view, and cards
100
    Project {
101
        #[command(subcommand)]
102
        cmd: ProjectCmd,
103
        /// A user or organisation other than the repository's owner
104
        #[arg(long, global = true)]
105
        owner: Option<String>,
106
    },
107
    /// AI assistants of the repository (its admins), or with --org or
108
    /// --site of an organisation or the site
109
    Assistant {
110
        #[command(subcommand)]
111
        cmd: AssistantCmd,
112
        /// An organisation's assistants instead of the repository's
113
        #[arg(long, global = true)]
114
        org: Option<String>,
115
        /// The site's assistants (administrators)
116
        #[arg(long, global = true, conflicts_with = "org")]
117
        site: bool,
118
    },
119
    /// Agents that act for you without a key of their own (keyless
120
    /// signing): grant, list, revoke
121
    Agent {
122
        #[command(subcommand)]
123
        cmd: AgentCmd,
124
    },
125
    /// Drops: small snippets of files, each its own repository, never
126
    /// listed among your repositories (oxygenhub#279)
127
    Drop {
128
        #[command(subcommand)]
129
        cmd: DropCmd,
130
    },
131
    /// Runners that update themselves (site administrators; oxygenhub#322):
132
    /// where builds come from, who takes them, what is held back
133
    #[command(name = "runner-updates")]
134
    RunnerUpdates {
135
        #[command(subcommand)]
136
        cmd: Option<RunnerUpdatesCmd>,
137
    },
138
    /// Serve this repository's hub to an AI agent over the Model Context Protocol (stdio); read-only unless --allow-write
139
    Mcp {
140
        /// Also offer tools that change the hub: create, comment on and close issues, comment on proposals, re-run Flow runs
141
        #[arg(long)]
142
        allow_write: bool,
143
    },
144
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
145
    Api {
146
        /// A path under /api/v1
147
        path: String,
148
        /// The method
149
        #[arg(long, short = 'X', default_value = "GET")]
150
        method: String,
151
        /// A JSON body
152
        #[arg(long, short = 'd')]
153
        data: Option<String>,
154
    },
155
}
156
157
#[derive(Subcommand)]
158
enum AgentCmd {
159
    /// Let an agent act for you: your oxy key (the one your oxy home names
160
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
161
    /// the agent a token it exchanges for ten-minute certificates. The
162
    /// token is printed once: give it to the agent (`oxy auth grant`)
163
    Grant {
164
        /// The agent's name, as in agent:NAME@YOU
165
        name: String,
166
        /// What its keys may do for you: changes, seal, refs
167
        #[arg(long, default_value = "changes,seal,refs")]
168
        scope: String,
169
        /// How long the grant lasts: 30d, 12h, 90m
170
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
171
        lasts: String,
172
    },
173
    /// Your grants, live and past
174
    List,
175
    /// Stop a grant at once: no more certificates under it
176
    Revoke { id: i64 },
177
}
178
179
#[derive(Subcommand)]
180
enum DropCmd {
181
    /// Make a drop of these files, signed by the hub as your delegate
182
    Create {
183
        /// The files (their names in the drop are their file names)
184
        #[arg(required = true)]
185
        files: Vec<std::path::PathBuf>,
186
        /// Unlisted: readable by anyone with its address, listed nowhere
187
        #[arg(long)]
188
        secret: bool,
189
        /// A description
190
        #[arg(long, short = 'd', value_name = "TEXT")]
191
        description: Option<String>,
192
        /// A title (default: the first file's name)
193
        #[arg(long, short = 't')]
194
        title: Option<String>,
195
    },
196
    /// Your drops, or someone's public ones
197
    List {
198
        /// Whose drops
199
        #[arg(long, short = 'u', value_name = "NAME")]
200
        user: Option<String>,
201
    },
202
    /// A drop's files, printed (by id or address)
203
    View {
204
        /// The drop's id, or its address
205
        id: String,
206
        /// Print only this file's content
207
        #[arg(long, short = 'f', value_name = "NAME")]
208
        file: Option<String>,
209
    },
210
    /// Delete a drop and its history
211
    Delete {
212
        /// The drop's id, or its address
213
        id: String,
214
    },
215
    /// A copy of someone's drop, history and all, as a drop of yours
216
    Fork {
217
        /// The drop's id, or its address
218
        id: String,
219
    },
220
    /// Star a drop
221
    Star {
222
        /// The drop's id, or its address
223
        id: String,
224
    },
225
    /// Take your star back
226
    Unstar {
227
        /// The drop's id, or its address
228
        id: String,
229
    },
230
    /// A drop's comments, oldest first
231
    Comments {
232
        /// The drop's id, or its address
233
        id: String,
234
    },
235
    /// Comment on a drop (Markdown); its owner is told
236
    Comment {
237
        /// The drop's id, or its address
238
        id: String,
239
        /// What to say
240
        #[arg(long, short = 'm')]
241
        message: String,
242
    },
243
}
244
245
#[derive(Subcommand)]
246
enum RunnerUpdatesCmd {
247
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
248
    Show,
249
    /// Change one level's settings; what is not given stays as it is
250
    Set {
251
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
252
        scope: String,
253
        /// `on`, `off` or `inherit`
254
        #[arg(long)]
255
        updates: Option<String>,
256
        /// `stable`, `canary`, a version, or `inherit`
257
        #[arg(long)]
258
        channel: Option<String>,
259
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
260
        #[arg(long)]
261
        window: Option<String>,
262
        /// `on`, `off` or `inherit`
263
        #[arg(long)]
264
        dry_run: Option<String>,
265
    },
266
    /// Offer a held build again (it rolled back on a runner)
267
    Lift { version: String },
268
}
269
270
#[derive(Subcommand)]
271
enum AuthCmd {
272
    /// Sign in to a hub and make it the default: approve a code on the web
273
    /// (device sign-in), or give a token
274
    Login {
275
        /// The hub, e.g. https://oxygenhub.io
276
        #[arg(long = "with-hub", value_name = "URL")]
277
        url: String,
278
        /// An API token from the hub's Settings → Tokens, instead of
279
        /// approving a code ("-" reads it from stdin)
280
        #[arg(long)]
281
        token: Option<String>,
282
        /// The hub's CA certificate, when self-signed
283
        #[arg(long)]
284
        ca: Option<std::path::PathBuf>,
285
    },
286
    /// Who the token in use belongs to
287
    Status,
288
}
289
290
#[derive(Subcommand)]
291
enum RepoCmd {
292
    /// Name, description, visibility and default bookmark
293
    View,
294
    /// Create a repository on the hub (#360): OWNER/NAME, with a board and
295
    /// starting files if asked
296
    Create {
297
        /// OWNER/NAME
298
        slug: String,
299
        #[arg(long, short)]
300
        description: Option<String>,
301
        /// public (the default), internal or private
302
        #[arg(long, default_value = "public")]
303
        visibility: String,
304
        /// A project board with it: `new`, `new:TITLE`, or an existing board's number
305
        #[arg(long, short)]
306
        project: Option<String>,
307
        /// Start it with a README
308
        #[arg(long)]
309
        readme: bool,
310
        /// Start it with a licence: MIT, BSD-2-Clause or ISC
311
        #[arg(long)]
312
        licence: Option<String>,
313
        /// Start it with an .oxyignore for a language: Rust, Node, Python, Go, "Java and Kotlin"
314
        #[arg(long)]
315
        ignore: Option<String>,
316
    },
317
}
318
319
#[derive(Subcommand)]
320
enum IssueCmd {
321
    /// Put labels on an issue or take them off (triage)
322
    Label(LabelChange),
323
    /// Open issues (or --state closed|all)
324
    List {
325
        #[arg(long, default_value = "open")]
326
        state: String,
327
    },
328
    /// One issue with its comments
329
    View { number: i64 },
330
    /// Open an issue
331
    Create {
332
        #[arg(long, short)]
333
        title: String,
334
        #[arg(long, short)]
335
        body: Option<String>,
336
        /// Read the body from a file ("-" for stdin)
337
        #[arg(long, short = 'F')]
338
        body_file: Option<String>,
339
        /// A label (repeatable)
340
        #[arg(long, short)]
341
        label: Vec<String>,
342
        /// Also put it on this board of the repository's owner
343
        #[arg(long, short)]
344
        project: Option<i64>,
345
        /// The board's column for it, by name (default: the first)
346
        #[arg(long, requires = "project")]
347
        column: Option<String>,
348
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
349
        #[arg(long, short = 'a', value_name = "FILE")]
350
        attach: Vec<std::path::PathBuf>,
351
    },
352
    /// Close an issue, with an optional comment saying why
353
    Close {
354
        number: i64,
355
        /// `completed` or `not_planned`
356
        #[arg(long, default_value = "completed")]
357
        reason: String,
358
        #[command(flatten)]
359
        comment: StateComment,
360
    },
361
    /// Reopen an issue, with an optional comment saying why
362
    Reopen {
363
        number: i64,
364
        #[command(flatten)]
365
        comment: StateComment,
366
    },
367
    /// Change an issue's title or body (its author or triage), or its
368
    /// labels, assignees or milestone as whole sets (triage)
369
    Edit {
370
        number: i64,
371
        #[arg(long, short)]
372
        title: Option<String>,
373
        #[arg(long, short)]
374
        body: Option<String>,
375
        /// Read the body from a file ("-" for stdin)
376
        #[arg(long, short = 'F', conflicts_with = "body")]
377
        body_file: Option<String>,
378
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
379
        #[arg(long, short)]
380
        label: Vec<String>,
381
        /// Clear its labels
382
        #[arg(long, conflicts_with = "label")]
383
        no_labels: bool,
384
        /// The users it should be assigned to (repeatable)
385
        #[arg(long, short)]
386
        assignee: Vec<String>,
387
        /// Take everyone off it
388
        #[arg(long, conflicts_with = "assignee")]
389
        no_assignees: bool,
390
        /// A milestone's title ("" takes it out of its milestone)
391
        #[arg(long, short)]
392
        milestone: Option<String>,
393
    },
394
    /// Comment on an issue
395
    Comment {
396
        number: i64,
397
        #[arg(long, short)]
398
        body: Option<String>,
399
        /// Read the body from a file ("-" for stdin), as proposal comment
400
        /// does (#260)
401
        #[arg(long, short = 'F', conflicts_with = "body")]
402
        body_file: Option<String>,
403
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
404
        #[arg(long, short = 'a', value_name = "FILE")]
405
        attach: Vec<std::path::PathBuf>,
406
    },
407
}
408
409
#[derive(Subcommand)]
410
enum ProposalCmd {
411
    /// Open proposals (or --state draft|landed|closed|all), newest first
412
    List {
413
        #[arg(long, default_value = "open")]
414
        state: String,
415
        /// At most this many
416
        #[arg(long, default_value_t = 30)]
417
        limit: usize,
418
    },
419
    /// One proposal: its changes, approvals and whether it can land
420
    View { number: i64 },
421
    /// Propose a bookmark's changes for another bookmark
422
    Create {
423
        #[arg(long, short)]
424
        title: String,
425
        #[arg(long, short)]
426
        body: Option<String>,
427
        /// Read the body from a file ("-" for stdin)
428
        #[arg(long, short = 'F', conflicts_with = "body")]
429
        body_file: Option<String>,
430
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
431
        #[arg(long)]
432
        from: String,
433
        /// The bookmark to land them on (default: the repository's default bookmark)
434
        #[arg(long)]
435
        into: Option<String>,
436
        #[arg(long)]
437
        draft: bool,
438
    },
439
    /// Change a proposal's title or description (its author or a maintainer)
440
    Edit {
441
        number: i64,
442
        #[arg(long, short)]
443
        title: Option<String>,
444
        #[arg(long, short)]
445
        body: Option<String>,
446
        /// Read the body from a file ("-" for stdin)
447
        #[arg(long, short = 'F', conflicts_with = "body")]
448
        body_file: Option<String>,
449
    },
450
    /// Put labels on a proposal or take them off (triage)
451
    Label(LabelChange),
452
    /// Comment on a proposal's conversation
453
    Comment {
454
        number: i64,
455
        #[arg(long, short)]
456
        body: Option<String>,
457
        /// Read the comment from a file ("-" for stdin)
458
        #[arg(long, short = 'F', conflicts_with = "body")]
459
        body_file: Option<String>,
460
    },
461
    /// The checks on a proposal's projected state
462
    Checks { number: i64 },
463
    /// Land a proposal on its target, as the page's Land button does
464
    Land {
465
        number: i64,
466
        /// Land before its required checks pass, saying why (maintainers;
467
        /// recorded and audited, #261)
468
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
469
        over_checks: Option<String>,
470
        /// Land it by itself once its checks pass (#261); with --off, don't
471
        #[arg(long)]
472
        when_ready: bool,
473
        /// With --when-ready: turn it off
474
        #[arg(long, requires = "when_ready")]
475
        off: bool,
476
    },
477
    /// Close a proposal without landing it, with an optional comment
478
    Close {
479
        number: i64,
480
        /// Say why, as a comment before it closes
481
        #[arg(long, short = 'm')]
482
        message: Option<String>,
483
    },
484
    /// Reopen a closed proposal
485
    Reopen { number: i64 },
486
    /// Take a draft proposal out of draft, ready for review (its author or triage)
487
    Ready {
488
        number: i64,
489
        /// Turn an open proposal back into a draft instead
490
        #[arg(long)]
491
        undo: bool,
492
    },
493
}
494
495
#[derive(Subcommand)]
496
enum AssistantCmd {
497
    /// The assistants this level sees, its own and those inherited
498
    List,
499
    /// Add an assistant, or change the one of that name
500
    Add {
501
        /// How it shows on reviews (default: the provider's name)
502
        #[arg(long, default_value = "")]
503
        name: String,
504
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
505
        #[arg(long, default_value = "")]
506
        preset: String,
507
        /// The endpoint, when no preset or another one
508
        #[arg(long, default_value = "")]
509
        endpoint: String,
510
        /// chat-completions or anthropic-messages
511
        #[arg(long, default_value = "")]
512
        api: String,
513
        /// One the endpoint lists (`oh assistant models` shows them)
514
        #[arg(long)]
515
        model: String,
516
        /// The API key, read from this environment variable (never typed on the command line)
517
        #[arg(long, value_name = "VAR")]
518
        token_env: Option<String>,
519
        /// Add it turned off
520
        #[arg(long)]
521
        off: bool,
522
    },
523
    /// Remove this level's assistant of that name
524
    Remove { name: String },
525
    /// Show this level's prompt, and those it inherits
526
    Prompt {
527
        /// Set it from this file (`-` for standard input; an empty file clears it)
528
        #[arg(long, value_name = "FILE")]
529
        set: Option<std::path::PathBuf>,
530
    },
531
}
532
533
#[derive(Subcommand)]
534
enum LabelCmd {
535
    /// The repository's labels
536
    List,
537
    /// Create a label, or change the one of that name (triage)
538
    Create {
539
        name: String,
540
        /// `#rrggbb` (default: one the hub picks)
541
        #[arg(long)]
542
        colour: Option<String>,
543
        #[arg(long, short, default_value = "")]
544
        description: String,
545
    },
546
    /// Delete a label, taking it off every issue and proposal (triage)
547
    Delete { name: String },
548
}
549
550
#[derive(Subcommand)]
551
enum ProjectCmd {
552
    /// The owner's boards
553
    List,
554
    /// One board: its columns and cards
555
    View {
556
        number: i64,
557
        /// Its archived cards instead (#293)
558
        #[arg(long)]
559
        archived: bool,
560
        /// Only the cards this filter keeps, as the board's filter bar takes it:
561
        /// words, repo:, assignee:, label:, milestone:, is:open|closed, age:>14d (#361)
562
        #[arg(long, short = 'q', conflicts_with = "view")]
563
        filter: Option<String>,
564
        /// A saved view of the board, by name: its filter (#361)
565
        #[arg(long)]
566
        view: Option<String>,
567
    },
568
    /// Create a board (owner, or an organisation's members)
569
    Create {
570
        title: String,
571
        #[arg(long, short, default_value = "")]
572
        description: String,
573
        /// Only the owner (or the organisation's members) can see it
574
        #[arg(long)]
575
        private: bool,
576
    },
577
    /// Close a board
578
    Close { number: i64 },
579
    /// Reopen a board
580
    Reopen { number: i64 },
581
    /// Move a board to another owner you may make boards under (an
582
    /// organisation, say); it takes the next number there
583
    Transfer {
584
        number: i64,
585
        /// The new owner
586
        #[arg(long)]
587
        to: String,
588
    },
589
    /// Cards on a board: add, move, archive, restore, remove
590
    Card {
591
        #[command(subcommand)]
592
        cmd: CardCmd,
593
    },
594
    /// A board's charts from its own history: forecasts, cycle time,
595
    /// throughput (#357)
596
    Charts {
597
        /// The board
598
        number: i64,
599
        /// Forecast only the cards this filter keeps (words, repo:, label:, milestone:…)
600
        #[arg(long, short = 'q')]
601
        filter: Option<String>,
602
    },
603
    /// A board's columns: add, rename, move, remove (#366)
604
    Column {
605
        #[command(subcommand)]
606
        cmd: ColumnCmd,
607
    },
608
}
609
610
#[derive(Subcommand)]
611
enum ColumnCmd {
612
    /// Add a column at the right
613
    Add {
614
        /// The board
615
        number: i64,
616
        name: String,
617
    },
618
    /// Rename a column (by name or id)
619
    Rename {
620
        /// The board
621
        number: i64,
622
        column: String,
623
        /// Its new name
624
        to: String,
625
    },
626
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
627
    Move {
628
        /// The board
629
        number: i64,
630
        column: String,
631
        /// Its place, counting from 1 at the left
632
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
633
        to: Option<i64>,
634
        /// One place to the left
635
        #[arg(long, conflicts_with = "right")]
636
        left: bool,
637
        /// One place to the right
638
        #[arg(long)]
639
        right: bool,
640
    },
641
    /// Remove a column; its cards go to the first remaining one
642
    Remove {
643
        /// The board
644
        number: i64,
645
        column: String,
646
    },
647
}
648
649
#[derive(Subcommand)]
650
enum CardCmd {
651
    /// Put an issue or proposal on a board (`12` or `#12` in this
652
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
653
    /// or a note with --note
654
    Add {
655
        number: i64,
656
        /// The issue or proposal; a number means this repository's
657
        reference: Option<String>,
658
        /// A note card instead
659
        #[arg(long, conflicts_with = "reference")]
660
        note: Option<String>,
661
        /// The column, by name or id (default: the first)
662
        #[arg(long, short)]
663
        column: Option<String>,
664
    },
665
    /// Move a card to another column (by name or id), or with --from every
666
    /// card of a column at once
667
    Move {
668
        number: i64,
669
        /// The card (its id); leave it out with --from
670
        card: Option<i64>,
671
        #[arg(long, short)]
672
        column: String,
673
        /// Move every card of this column (#289)
674
        #[arg(long, conflicts_with = "card")]
675
        from: Option<String>,
676
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
677
        #[arg(long, value_delimiter = ',', requires = "from")]
678
        except: Vec<String>,
679
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
680
        #[arg(long, value_delimiter = ',', requires = "from")]
681
        state: Vec<String>,
682
        /// With --from: say what would move, and move nothing
683
        #[arg(long, requires = "from")]
684
        dry_run: bool,
685
    },
686
    /// Archive a column's cards: off the board, kept and restorable (#293)
687
    Archive {
688
        number: i64,
689
        /// The column, by name or id
690
        #[arg(long)]
691
        from: String,
692
        /// Only cards that joined the column more than this long ago (14d, or 14)
693
        #[arg(long)]
694
        older: Option<String>,
695
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
696
        #[arg(long, value_delimiter = ',')]
697
        except: Vec<String>,
698
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
699
        #[arg(long, value_delimiter = ',')]
700
        state: Vec<String>,
701
        /// Say what would be archived, and archive nothing
702
        #[arg(long)]
703
        dry_run: bool,
704
    },
705
    /// Put an archived card back at the end of its column
706
    Restore { number: i64, card: i64 },
707
    /// Take a card off a board
708
    Remove { number: i64, card: i64 },
709
}
710
711
#[derive(Subcommand)]
712
enum MilestoneCmd {
713
    /// The repository's milestones
714
    List,
715
    /// Create a milestone, or change the one of that title (triage)
716
    Create {
717
        title: String,
718
        #[arg(long, short, default_value = "")]
719
        description: String,
720
        /// Due date, YYYY-MM-DD
721
        #[arg(long)]
722
        due: Option<String>,
723
    },
724
    /// Change a milestone's title, description or due date (triage)
725
    Edit {
726
        title: String,
727
        #[arg(long, short)]
728
        rename: Option<String>,
729
        #[arg(long, short)]
730
        description: Option<String>,
731
        /// Due date, YYYY-MM-DD ("" for none)
732
        #[arg(long)]
733
        due: Option<String>,
734
    },
735
    /// Close a milestone
736
    Close { title: String },
737
    /// Reopen a milestone
738
    Reopen { title: String },
739
}
740
741
/// Labels to put on or take off an issue or proposal.
742
#[derive(clap::Args)]
743
struct LabelChange {
744
    number: i64,
745
    /// A label to add (repeatable)
746
    #[arg(long, short)]
747
    add: Vec<String>,
748
    /// A label to take off (repeatable)
749
    #[arg(long, short)]
750
    remove: Vec<String>,
751
}
752
753
impl LabelChange {
754
    /// The set after the change, from the one there now.
7550×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
7560×
        if self.add.is_empty() && self.remove.is_empty() {
7570×
            bail!("say what to change: --add NAME or --remove NAME");
7580×
        }
7590×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
7600×
        for a in &self.add {
7610×
            if !names.contains(a) {
7620×
                names.push(a.clone());
7630×
            }
764
        }
7650×
        Ok(names)
7660×
    }
767
}
768
7690×
fn label_names(labels: &[String]) -> String {
7700×
    if labels.is_empty() {
7710×
        ui::dim("no labels")
772
    } else {
7730×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
774
    }
7750×
}
776
777
#[derive(Subcommand)]
778
enum CoverageCmd {
779
    /// Upload an LCOV or Cobertura report measured on this machine, as the
780
    /// coverage of a bookmark's current state (default: the default
781
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
782
    /// not measured by a runner, and sets no check from it
783
    Upload {
784
        file: std::path::PathBuf,
785
        #[arg(long)]
786
        bookmark: Option<String>,
787
        /// A change's full hash
788
        #[arg(long, conflicts_with = "bookmark")]
789
        change: Option<String>,
790
    },
791
}
792
793
#[derive(Subcommand)]
794
enum RunCmd {
795
    /// Recent runs, newest first
796
    List {
797
        #[arg(long, default_value_t = 20)]
798
        limit: i64,
799
    },
800
    /// A run and its jobs (default: the newest run)
801
    View {
802
        /// The run (default: the newest, or the newest of --bookmark)
803
        number: Option<i64>,
804
        /// With no number: the newest run of this bookmark
805
        #[arg(long, conflicts_with = "number")]
806
        bookmark: Option<String>,
807
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
808
        #[arg(long)]
809
        timings: bool,
810
    },
811
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
812
    Start {
813
        #[arg(long)]
814
        bookmark: Option<String>,
815
        /// A change's full hash
816
        #[arg(long, conflicts_with = "bookmark")]
817
        change: Option<String>,
818
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
819
        #[arg(long = "job", value_name = "NAME")]
820
        jobs: Vec<String>,
821
        /// Wait for the run and exit 1 unless it passes
822
        #[arg(long)]
823
        watch: bool,
824
    },
825
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
826
    Watch {
827
        /// The run (default: the newest, or the newest of --bookmark) (#367)
828
        number: Option<i64>,
829
        /// With no number: the newest run of this bookmark
830
        #[arg(long, conflicts_with = "number")]
831
        bookmark: Option<String>,
832
    },
833
    /// A job's log
834
    Log { number: i64, job: String },
835
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
836
    Report {
837
        number: i64,
838
        job: String,
839
        #[command(flatten)]
840
        pick: ReportPick,
841
    },
842
    /// Run a finished run's state again; with --job, only that job (and the
843
    /// jobs that depend on it) in the same run
844
    Rerun {
845
        number: i64,
846
        #[arg(long)]
847
        job: Option<String>,
848
    },
849
    /// Cancel a run still queued or running; its running jobs are stopped
850
    Cancel { number: i64 },
851
    /// Approve a job that waits for a person (oxygenflow#57)
852
    Approve {
853
        number: i64,
854
        #[arg(long)]
855
        job: String,
856
    },
857
    /// Reject a job that waits for a person: it ends cancelled
858
    Reject {
859
        number: i64,
860
        #[arg(long)]
861
        job: String,
862
    },
863
}
864
865
/// Which report of a job, and what of it to show.
866
#[derive(clap::Args)]
867
struct ReportPick {
868
    /// Which report, when the job published more than one
869
    #[arg(long)]
870
    name: Option<String>,
871
    /// What it holds: its metrics, context and files
872
    #[arg(long, conflicts_with = "file")]
873
    list: bool,
874
    /// One file of it (`data/frames.csv`), as published
875
    #[arg(long, value_name = "PATH")]
876
    file: Option<String>,
877
    /// Write the file here instead of to stdout
878
    #[arg(long, short, value_name = "FILE", requires = "file")]
879
    output: Option<std::path::PathBuf>,
880
}
881
882
#[derive(Subcommand)]
883
enum ReportCmd {
884
    /// The newest run of each report, newest first
885
    List {
886
        /// Only runs on this bookmark
887
        #[arg(long)]
888
        bookmark: Option<String>,
889
    },
890
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
891
    Show {
892
        report: String,
893
        #[arg(long, conflicts_with = "bookmark")]
894
        id: Option<i64>,
895
        #[arg(long)]
896
        bookmark: Option<String>,
897
        /// What it holds: its metrics, context and files
898
        #[arg(long, conflicts_with = "file")]
899
        list: bool,
900
        /// One file of it, as published
901
        #[arg(long, value_name = "PATH")]
902
        file: Option<String>,
903
        /// Write the file here instead of to stdout
904
        #[arg(long, short, value_name = "FILE", requires = "file")]
905
        output: Option<std::path::PathBuf>,
906
    },
907
}
908
909
#[derive(Subcommand)]
910
enum TagCmd {
911
    /// Tags, newest name first
912
    List,
913
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
914
    /// delegate (as `oxy tag create` and a push would be)
915
    Create {
916
        name: String,
917
        /// What to tag (default: the default bookmark)
918
        #[arg(long)]
919
        target: Option<String>,
920
        #[arg(long, short)]
921
        message: Option<String>,
922
    },
923
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
924
    /// their next fetch, and the name is never used again. Refused while a
925
    /// release uses the tag
926
    Delete {
927
        name: String,
928
        /// Why, recorded with the withdrawal
929
        #[arg(long, short)]
930
        reason: Option<String>,
931
    },
932
}
933
934
#[derive(Subcommand)]
935
enum ReleaseCmd {
936
    /// Releases, newest first
937
    List,
938
    /// Create a release on an existing tag
939
    Create {
940
        tag: String,
941
        #[arg(long, short)]
942
        title: Option<String>,
943
        /// Notes in Markdown (default: generated from the changes since the previous release)
944
        #[arg(long, short)]
945
        notes: Option<String>,
946
        #[arg(long)]
947
        prerelease: bool,
948
    },
949
    /// Change a release's title, notes or prerelease flag
950
    Edit {
951
        tag: String,
952
        #[arg(long, short)]
953
        title: Option<String>,
954
        /// New notes in Markdown ("-" reads them from stdin)
955
        #[arg(long, short)]
956
        notes: Option<String>,
957
        /// Mark it a prerelease (true) or not (false)
958
        #[arg(long)]
959
        prerelease: Option<bool>,
960
    },
961
    /// Attach files to a release
962
    Upload { tag: String, files: Vec<std::path::PathBuf> },
963
    /// The release's trust report: signatures, builds, receipts and audit
964
    Trust { tag: String },
965
}
966
96753×
fn main() {
968
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
969
    // other command-line tools do, instead of panicking on the failed
970
    // write (oxygenhub#92).
971
    #[cfg(unix)]
97253×
    unsafe {
97353×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
97453×
    }
97553×
    let cli = Cli::parse();
97653×
    ui::init(cli.plain);
97753×
    match run(cli) {
97845×
        Ok(code) => std::process::exit(code),
9798×
        Err(e) => {
9808×
            eprintln!("{} {e:#}", ui::bad("error:"));
9818×
            std::process::exit(2);
982
        }
983
    }
984
}
985
98622×
fn enc(s: &str) -> String {
98722×
    let mut out = String::new();
988109×
    for b in s.bytes() {
989109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
990108×
            out.push(b as char);
991108×
        } else {
9921×
            out.push_str(&format!("%{b:02X}"));
9931×
        }
994
    }
99522×
    out
99622×
}
997
99853×
fn run(cli: Cli) -> Result<i32> {
99953×
    let cfg = Config::load()?;
10001×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
10011×
        return login(cfg, url, token.clone(), ca.clone());
100252×
    }
100352×
    let here = std::env::current_dir()?;
100452×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
100551×
    let c = Client::new(&t)?;
100651×
    let json = cli.json;
10070×
    match cli.cmd {
1008
        Cmd::Auth { cmd: AuthCmd::Status } => {
10090×
            let me: serde_json::Value = c.get("/user")?;
10100×
            if json {
10110×
                println!("{me}");
10120×
            } else {
10130×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
10140×
            }
10150×
            Ok(0)
1016
        }
10170×
        Cmd::Auth { .. } => unreachable!(),
10182×
        Cmd::Mcp { allow_write } => {
10192×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
10202×
            mcp::serve(c, t, allow_write)
1021
        }
10222×
        Cmd::Api { path, method, data } => {
10232×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
1024
            // The method applies with or without a body (#75): without one, a
1025
            // GET reads, anything else sends an empty object.
10262×
            let text = match data {
10270×
                Some(d) => c.send_text(
10280×
                    &method.to_uppercase(),
10290×
                    &path,
10300×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
10310×
                )?,
10322×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
10330×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
1034
            };
10352×
            println!("{text}");
10362×
            Ok(0)
1037
        }
10380×
        Cmd::Repo { cmd: RepoCmd::Create { slug, description, visibility, project, readme, licence, ignore } } => {
10390×
            let (owner, name) = slug.split_once('/').context("give the repository as OWNER/NAME")?;
10400×
            let project = match project.as_deref() {
10410×
                None => None,
10420×
                Some("new") => Some(serde_json::json!({ "new": "" })),
10430×
                Some(p) if p.starts_with("new:") => Some(serde_json::json!({ "new": &p[4..] })),
10440×
                Some(n) => {
10450×
                    Some(serde_json::json!({ "number": n.parse::<i64>().context("--project is new, new:TITLE or a board number")? }))
1046
                }
1047
            };
10480×
            let mut body = serde_json::json!({
10490×
                "owner": owner, "name": name, "description": description.unwrap_or_default(), "visibility": visibility, "readme": readme,
1050
            });
10510×
            if let Some(p) = project {
10520×
                body["project"] = p;
10530×
            }
10540×
            if let Some(l) = licence {
10550×
                body["licence"] = serde_json::json!(l);
10560×
            }
10570×
            if let Some(i) = ignore {
10580×
                body["ignore"] = serde_json::json!(i);
10590×
            }
10600×
            let r: serde_json::Value = c.send("POST", "/repos", &body)?;
10610×
            if json {
10620×
                println!("{r}");
10630×
            } else {
10640×
                println!("{} created {owner}/{name} {}", ui::ok("✔"), ui::dim(r["url"].as_str().unwrap_or("")));
10650×
                println!("{}", ui::kv("clone", &format!("oxy clone {}/{owner}/{name}", t.hub)));
10660×
            }
10670×
            Ok(0)
1068
        }
1069
        Cmd::Repo { cmd: RepoCmd::View } => {
10701×
            let path = t.repo_path()?;
10711×
            if json {
10720×
                println!("{}", c.get_text(&path)?);
10730×
                return Ok(0);
10741×
            }
10751×
            let r: serde_json::Value = c.get(&path)?;
10761×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
10771×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
10781×
                println!("{d}");
10791×
            }
10801×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
10811×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
10821×
            Ok(0)
1083
        }
108418×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
10854×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
10863×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
10870×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
10880×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
10890×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
10900×
            let mut body = serde_json::json!({ "content": content });
10910×
            if let Some(b) = bookmark {
10920×
                body["bookmark"] = b.into();
10930×
            }
10940×
            if let Some(ch) = change {
10950×
                body["change"] = ch.into();
10960×
            }
10970×
            let base = t.repo_path()?;
10980×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
10990×
            if json {
11000×
                println!("{}", serde_json::to_string(&r)?);
1101
            } else {
11020×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
11030×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
11040×
                println!(
1105
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
11060×
                    ui::ok("✔"),
1107
                    r.lines_hit,
1108
                    r.lines_found,
1109
                    r.files,
11100×
                    ui::dim(&r.url)
1111
                );
11120×
                if r.dropped > 0 {
11130×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
11140×
                }
1115
            }
11160×
            Ok(0)
1117
        }
11184×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
11190×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
11200×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
11210×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
112210×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
11230×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
11240×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
11250×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
11267×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1127
    }
112853×
}
1129
1130
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
11312×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
11322×
    Ok(match v {
11330×
        None => None,
11342×
        Some("on") => Some(Some(true)),
11352×
        Some("off") => Some(Some(false)),
11362×
        Some("inherit") => Some(None),
11371×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1138
    })
11392×
}
1140
1141
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
11427×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
11437×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
11441×
    Ok(match kind {
11457×
        "site" if name.is_empty() => ("site".into(), String::new()),
11466×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
11475×
        "group" => {
11483×
            let g = all
11493×
                .groups
11503×
                .iter()
11513×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
11523×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
11533×
            ("group".into(), g.id.to_string())
1154
        }
11552×
        "runner" => {
11561×
            let r = all
11571×
                .runners
11581×
                .iter()
11591×
                .find(|r| r.id.to_string() == name || r.name == name)
11601×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
11610×
            ("runner".into(), r.id.to_string())
1162
        }
11631×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1164
    })
11657×
}
1166
11670×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
11680×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
11690×
    match cmd {
11700×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1171
        RunnerUpdatesCmd::Show => {
11720×
            println!(
1173
                "{} {}",
11740×
                ui::strong("Builds from"),
11750×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1176
            );
11770×
            for h in &all.holds {
11780×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
11790×
            }
11800×
            for s in &all.settings {
11810×
                let mut said = vec![];
11820×
                if let Some(u) = s.updates {
11830×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
11840×
                }
11850×
                if let Some(ch) = &s.channel {
11860×
                    said.push(format!("channel {ch}"));
11870×
                }
11880×
                if let Some(w) = &s.window {
11890×
                    said.push(format!("window {w} UTC"));
11900×
                }
11910×
                if let Some(d) = s.dry_run {
11920×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
11930×
                }
11940×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
11950×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1196
            }
11970×
            for g in &all.groups {
11980×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
11990×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
12000×
                if let Some(w) = g.wave {
12010×
                    what.push_str(&format!(", wave {w}"));
12020×
                }
12030×
                println!(
1204
                    "  group {} ({what}): {}",
12050×
                    ui::strong(&g.name),
12060×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1207
                );
1208
            }
12090×
            for r in &all.runners {
12100×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
12110×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1212
            }
1213
        }
12140×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
12150×
            let (scope, key) = update_scope(&scope, &all)?;
12160×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
12170×
                scope: scope.clone(),
12180×
                key: key.clone(),
12190×
                ..Default::default()
12200×
            });
12210×
            if let Some(u) = switch(updates.as_deref())? {
12220×
                s.updates = u;
12230×
            }
12240×
            if let Some(d) = switch(dry_run.as_deref())? {
12250×
                s.dry_run = d;
12260×
            }
12270×
            if let Some(ch) = channel {
12280×
                s.channel = Some(ch).filter(|c| c != "inherit");
12290×
            }
12300×
            if let Some(w) = window {
12310×
                s.window = Some(w).filter(|w| w != "inherit");
12320×
            }
12330×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
12340×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1235
        }
12360×
        RunnerUpdatesCmd::Lift { version } => {
12370×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
12380×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1239
        }
1240
    }
12410×
    Ok(0)
12420×
}
1243
1244
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
12457×
fn drop_id(s: &str) -> Result<String> {
12467×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1247144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
12481×
        bail!("{s:?} is not a drop's id or address");
12496×
    }
12506×
    Ok(id.to_ascii_lowercase())
12517×
}
1252
12532×
fn drop_line(d: &hub_api::Drop) -> String {
12542×
    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() };
12554×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
12562×
    format!(
1257
        "{} {} {}{}",
12582×
        ui::dim(&d.id),
12592×
        ui::strong(&title),
12602×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
12612×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1262
    )
12632×
}
1264
1265
/// `oh drop star|unstar` (oxygenhub#349).
12660×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
12670×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
12680×
    if json {
12690×
        println!("{}", serde_json::to_string(&s)?);
1270
    } else {
12710×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1272
    }
12730×
    Ok(())
12740×
}
1275
12767×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
12777×
    match cmd {
12781×
        DropCmd::Create { files, secret, description, title } => {
12791×
            let mut out = Vec::with_capacity(files.len());
12802×
            for f in &files {
12812×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
12822×
                let content =
12832×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
12842×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1285
            }
12861×
            let new =
12871×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
12881×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
12891×
            if json {
12901×
                println!("{}", serde_json::to_string(&d)?);
1291
            } else {
12920×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
12930×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1294
            }
1295
        }
12962×
        DropCmd::List { user } => {
12972×
            let path = match &user {
12981×
                Some(u) => format!("/users/{}/drops", enc(u)),
12991×
                None => "/drops".to_string(),
1300
            };
13012×
            if json {
13021×
                println!("{}", c.get_text(&path)?);
13031×
                return Ok(0);
13041×
            }
13051×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
13061×
            if list.is_empty() {
13070×
                println!("{}", ui::dim("No drops."));
13081×
            }
13091×
            for d in &list {
13101×
                println!("{}", drop_line(d));
13111×
            }
1312
        }
13133×
        DropCmd::View { id, file } => {
13143×
            let path = format!("/drops/{}", drop_id(&id)?);
13153×
            if json && file.is_none() {
13160×
                println!("{}", c.get_text(&path)?);
13170×
                return Ok(0);
13183×
            }
13193×
            let d: hub_api::Drop = c.get(&path)?;
13202×
            if let Some(name) = file {
13212×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
13221×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
13231×
                print!("{content}");
13241×
                return Ok(0);
13251×
            }
13261×
            println!("{}", drop_line(&d));
13271×
            if !d.description.is_empty() {
13281×
                println!("{}", d.description);
13291×
            }
13301×
            println!("{}", ui::kv("url", &d.url));
13311×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
13322×
            for f in &d.files {
13332×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
13342×
                match &f.content {
13352×
                    Some(text) => {
13362×
                        print!("{text}");
13372×
                        if !text.ends_with('\n') && !text.is_empty() {
13380×
                            println!();
13392×
                        }
1340
                    }
13410×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1342
                }
1343
            }
1344
        }
13451×
        DropCmd::Delete { id } => {
13461×
            let id = drop_id(&id)?;
13471×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
13481×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1349
        }
13500×
        DropCmd::Fork { id } => {
13510×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
13520×
            if json {
13530×
                println!("{}", serde_json::to_string(&d)?);
13540×
            } else {
13550×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
13560×
            }
1357
        }
13580×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
13590×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
13600×
        DropCmd::Comments { id } => {
13610×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
13620×
            if json {
13630×
                println!("{}", c.get_text(&path)?);
13640×
                return Ok(0);
13650×
            }
13660×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
13670×
            if list.is_empty() {
13680×
                println!("{}", ui::dim("No comments."));
13690×
            }
13700×
            for m in &list {
13710×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
13720×
                println!("{}\n", m.body);
13730×
            }
1374
        }
13750×
        DropCmd::Comment { id, message } => {
13760×
            let m: hub_api::DropComment =
13770×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
13780×
            if json {
13790×
                println!("{}", serde_json::to_string(&m)?);
13800×
            } else {
13810×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
13820×
            }
1383
        }
1384
    }
13854×
    Ok(0)
13867×
}
1387
1388
/// `30d`, `12h`, `90m` in milliseconds.
13890×
fn duration_ms(s: &str) -> Result<i64> {
13900×
    let s = s.trim();
13910×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
13920×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
13930×
    let per = match unit {
13940×
        "d" => 86_400_000,
13950×
        "h" => 3_600_000,
13960×
        "m" => 60_000,
13970×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1398
    };
13990×
    if n <= 0 {
14000×
        bail!("a grant must last some time");
14010×
    }
14020×
    Ok(n * per)
14030×
}
1404
14050×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1406
    use oxy_core::cert::{Grant, SignedGrant};
1407
    use oxy_core::identity::{Identity, Scope};
14080×
    match cmd {
14090×
        AgentCmd::Grant { name, scope, lasts } => {
14100×
            let home = oxy_core::repo::default_home();
14110×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
14120×
                format!(
1413
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
14140×
                    home.display()
1415
                )
14160×
            })?;
14170×
            let me: serde_json::Value = c.get("/user")?;
14180×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
14190×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
14200×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
14210×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14220×
            let grant = Grant {
14230×
                grantor: me_id.hash(),
14240×
                subject: format!("agent:{name}@{username}"),
14250×
                issuer: hub.hash(),
14260×
                scope,
14270×
                not_before: (now - 60_000) as u64,
14280×
                expires: (now + duration_ms(&lasts)?) as u64,
1429
            };
14300×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
14310×
            let r: serde_json::Value =
14320×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
14330×
            if json {
14340×
                println!("{r}");
14350×
                return Ok(0);
14360×
            }
14370×
            println!(
1438
                "{} {} to act for you as {} ({}), until {}",
14390×
                ui::ok("✔ granted"),
14400×
                ui::strong(&name),
14410×
                r["subject"].as_str().unwrap_or(""),
14420×
                r["scope"].as_str().unwrap_or(""),
14430×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1444
            );
14450×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
14460×
            println!(
1447
                "  {}",
14480×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1449
            );
14500×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
14510×
            Ok(0)
1452
        }
1453
        AgentCmd::List => {
14540×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
14550×
            if json {
14560×
                println!("{}", serde_json::to_string(&grants)?);
14570×
                return Ok(0);
14580×
            }
14590×
            if grants.is_empty() {
14600×
                println!("{}", ui::dim("no agent grants"));
14610×
            }
14620×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14630×
            for g in grants {
14640×
                let state = if g["revoked_ms"].is_i64() {
14650×
                    ui::bad("revoked")
14660×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
14670×
                    ui::dim("ended")
1468
                } else {
14690×
                    ui::ok("live")
1470
                };
14710×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
14720×
                println!(
1473
                    "#{:<4} {:<8} {} · {} · until {} · {}",
14740×
                    g["id"],
1475
                    state,
14760×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
14770×
                    g["scope"].as_str().unwrap_or(""),
14780×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
14790×
                    ui::dim(&used)
1480
                );
1481
            }
14820×
            Ok(0)
1483
        }
14840×
        AgentCmd::Revoke { id } => {
14850×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
14860×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
14870×
            Ok(0)
1488
        }
1489
    }
14900×
}
1491
14921×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
14931×
    let hub = url.trim_end_matches('/').to_string();
14941×
    let token = match token.as_deref() {
14951×
        Some("-") => {
14960×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
14970×
            let mut line = String::new();
14980×
            std::io::stdin().read_line(&mut line)?;
14990×
            line.trim().to_string()
1500
        }
15011×
        Some(t) => t.to_string(),
15020×
        None => device_sign_in(&hub, ca.clone())?,
1503
    };
15041×
    if token.is_empty() {
15050×
        bail!("no token given");
15061×
    }
15071×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
15081×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
15091×
    let account = me["username"].as_str().unwrap_or("?");
1510
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
15111×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
15121×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
15131×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
15141×
    cfg.default_hub = Some(hub.clone());
15151×
    cfg.save()?;
15161×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
15171×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
15181×
    Ok(0)
15191×
}
1520
1521
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1522
/// it on the web, and the token arrives here.
15230×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
15240×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
15250×
    let c = Client::new(&t)?;
15260×
    let host = std::fs::read_to_string("/etc/hostname")
15270×
        .ok()
15280×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
15290×
        .map(|h| h.trim().to_string())
15300×
        .filter(|h| !h.is_empty());
15310×
    let client = match host {
15320×
        Some(h) => format!("oh on {h}"),
15330×
        None => "oh".to_string(),
1534
    };
15350×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
15360×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
15370×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
15380×
    if code != 200 {
15390×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
15400×
    }
15410×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
15420×
    let user = v["user_code"].as_str().unwrap_or("?");
15430×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
15440×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
15450×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
15460×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
15470×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1548
    loop {
15490×
        std::thread::sleep(std::time::Duration::from_secs(interval));
15500×
        if std::time::Instant::now() > deadline {
15510×
            bail!("the code expired before it was approved; run oh auth login again");
15520×
        }
15530×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
15540×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
15550×
        if code == 200 {
15560×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
15570×
        }
15580×
        match v["error"].as_str() {
15590×
            Some("authorization_pending") => {}
15600×
            Some("slow_down") => interval += 5,
15610×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
15620×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
15630×
            _ => bail!("signing in: HTTP {code}: {body}"),
1564
        }
1565
    }
15660×
}
1567
156810×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
156910×
    match (body, file) {
15703×
        (Some(b), _) => Ok(b),
15711×
        (None, Some(f)) if f == "-" => {
15720×
            let mut s = String::new();
15730×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
15740×
            Ok(s)
1575
        }
15761×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
15776×
        (None, None) => Ok(String::new()),
1578
    }
157910×
}
1580
15813×
fn issue_line(i: &Issue) -> String {
15823×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
15833×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
15843×
    format!(
1585
        "{glyph} {} {}{}{}",
15863×
        ui::dim(&format!("#{}", i.number)),
1587
        i.title,
15883×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
15893×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1590
    )
15913×
}
1592
159318×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
159418×
    let base = t.repo_path()?;
159518×
    match cmd {
15963×
        IssueCmd::List { state } => {
15973×
            let path = format!("{base}/issues?state={}", enc(&state));
15983×
            if json {
15991×
                println!("{}", c.get_text(&path)?);
16001×
                return Ok(0);
16012×
            }
16022×
            let list: Vec<Issue> = c.get(&path)?;
16032×
            if list.is_empty() {
16041×
                println!("{}", ui::dim(&format!("No {state} issues.")));
16051×
            }
16062×
            for i in &list {
16072×
                println!("{}", issue_line(i));
16082×
            }
1609
        }
16102×
        IssueCmd::View { number } => {
16112×
            let path = format!("{base}/issues/{number}");
16122×
            if json {
16131×
                println!("{}", c.get_text(&path)?);
16141×
                return Ok(0);
16151×
            }
16161×
            let i: Issue = c.get(&path)?;
16171×
            println!("{}", issue_line(&i));
16181×
            if !i.body.trim().is_empty() {
16191×
                println!("\n{}\n", i.body.trim_end());
16201×
            }
16211×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
16222×
            for cm in comments {
16232×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
16242×
            }
16251×
            println!("{}", ui::dim(&i.url));
1626
        }
16274×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
16284×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16294×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
16304×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
16313×
            if json {
16321×
                println!("{}", serde_json::to_string(&i)?);
16332×
            } else {
16342×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16352×
            }
16363×
            if let Some(n) = project {
16371×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
16381×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
16391×
                if !json {
16401×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
16411×
                }
16422×
            }
1643
        }
16441×
        IssueCmd::Close { number, reason, comment } => {
16451×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
16461×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
16471×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1648
        }
16490×
        IssueCmd::Reopen { number, comment } => {
16500×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
16510×
            let i: Issue =
16520×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
16530×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1654
        }
16553×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
16563×
            let body = match (&body, &body_file) {
16573×
                (None, None) => None,
16580×
                _ => Some(body_of(body, body_file)?),
1659
            };
16603×
            let labels = if no_labels {
16611×
                Some(Vec::new())
16622×
            } else if label.is_empty() {
16631×
                None
1664
            } else {
16651×
                Some(label)
1666
            };
16673×
            let assignees = if no_assignees {
16681×
                Some(Vec::new())
16692×
            } else if assignee.is_empty() {
16701×
                None
1671
            } else {
16721×
                Some(assignee)
1673
            };
16743×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
16751×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
16762×
            }
16772×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
16782×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
16792×
            if json {
16801×
                println!("{}", serde_json::to_string(&i)?);
16811×
            } else {
16821×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16831×
            }
1684
        }
16850×
        IssueCmd::Label(change) => {
16860×
            let path = format!("{base}/issues/{}", change.number);
16870×
            let now: Issue = c.get(&path)?;
16880×
            let labels = change.apply(&now.labels)?;
16890×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
16900×
            let i: Issue = c.send("PATCH", &path, &edit)?;
16910×
            if json {
16920×
                println!("{}", serde_json::to_string(&i)?);
16930×
            } else {
16940×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
16950×
            }
1696
        }
16975×
        IssueCmd::Comment { number, body, body_file, attach } => {
16985×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16994×
            if body.trim().is_empty() {
17001×
                bail!("give the comment with --body, --body-file or --attach");
17013×
            }
17023×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
17033×
            println!("{} commented on #{number}", ui::ok("✔"));
1704
        }
1705
    }
170612×
    Ok(0)
170718×
}
1708
1709
/// A comment to post with a close or reopen (#368): saying why, in the
1710
/// same command.
1711
#[derive(clap::Args)]
1712
struct StateComment {
1713
    /// Say why, as a comment posted first
1714
    #[arg(long, short)]
1715
    body: Option<String>,
1716
    /// Read the comment from a file ("-" for stdin)
1717
    #[arg(long, short = 'F', conflicts_with = "body")]
1718
    body_file: Option<String>,
1719
    /// Attach a file to the comment (repeatable)
1720
    #[arg(long, short = 'a', value_name = "FILE")]
1721
    attach: Vec<std::path::PathBuf>,
1722
}
1723
1724
impl StateComment {
17251×
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
17261×
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
17271×
            return Ok(());
17280×
        }
17290×
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
17300×
        if !body.trim().is_empty() {
17310×
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
17320×
        }
17330×
        Ok(())
17341×
    }
1735
}
1736
1737
/// `number`, or the newest run (of `bookmark`, when given): what a push
1738
/// just started is what one usually wants to follow (#367).
17391×
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
17401×
    if let Some(n) = number {
17411×
        return Ok(n);
17420×
    }
17430×
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
17440×
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
17450×
        Some(b) => format!("no runs of {b} among the latest 100"),
17460×
        None => "no runs yet".to_string(),
17470×
    })
17481×
}
1749
1750
/// `body` with each file attached to the repository and linked under it:
1751
/// an image shown in place, anything else a download (#350). Files are
1752
/// uploaded first, so a failed upload leaves nothing half made.
17539×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
17549×
    if files.is_empty() {
17556×
        return Ok(body);
17563×
    }
17573×
    let mut links = Vec::new();
17584×
    for f in files {
17594×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
17603×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
17613×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
17623×
        let a: hub_api::Attachment =
17633×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
17643×
        links.push(a.markdown);
1765
    }
17662×
    let links = links.join("\n\n");
17672×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
17689×
}
1769
17701×
fn source_name(s: &hub_api::ProposalSource) -> String {
17711×
    match s {
17721×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
17730×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
17740×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1775
    }
17761×
}
1777
17781×
fn proposal_line(p: &Proposal) -> String {
17791×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
17801×
    let glyph = match state.as_str() {
17811×
        "open" => ui::ok("●"),
17820×
        "draft" => ui::dim("◌"),
17830×
        "landed" => ui::strong("✔"),
17840×
        _ => ui::dim("○"),
1785
    };
17861×
    format!(
1787
        "{glyph} {} {} {}{}",
17881×
        ui::dim(&format!("#{}", p.number)),
1789
        p.title,
17901×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
17911×
        ui::dim(&format!(" · {} · {state}", p.author))
1792
    )
17931×
}
1794
17954×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
17964×
    let base = t.repo_path()?;
17974×
    match cmd {
17980×
        ProposalCmd::List { state, limit } => {
17990×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
18000×
            if json {
18010×
                println!("{}", c.get_text(&path)?);
18020×
                return Ok(0);
18030×
            }
18040×
            let list: Vec<Proposal> = c.get(&path)?;
18050×
            if list.is_empty() {
18060×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
18070×
            }
18080×
            for p in &list {
18090×
                println!("{}", proposal_line(p));
18100×
            }
1811
        }
18121×
        ProposalCmd::View { number } => {
18131×
            let path = format!("{base}/proposals/{number}");
18141×
            if json {
18150×
                println!("{}", c.get_text(&path)?);
18160×
                return Ok(0);
18171×
            }
18181×
            let p: Proposal = c.get(&path)?;
18191×
            println!("{}", proposal_line(&p));
18201×
            if !p.body.trim().is_empty() {
18210×
                println!("\n{}\n", p.body.trim_end());
18221×
            }
18231×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
18241×
            for ch in &p.changes {
18251×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
18261×
            }
18271×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
18281×
            if p.landable {
18291×
                println!("{} can land", ui::ok("✔"));
18301×
            } else {
18310×
                for b in &p.blockers {
18320×
                    println!("{} {b}", ui::bad("✘"));
18330×
                }
1834
            }
18351×
            if p.conflicted {
18360×
                println!("{} landing it would leave conflicts", ui::bad("!"));
18371×
            }
18381×
            println!("{}", ui::dim(&p.url));
1839
        }
18401×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
18411×
            let target = match into {
18420×
                Some(i) => i,
18431×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1844
            };
18451×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
18461×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
18471×
            if json {
18480×
                println!("{}", serde_json::to_string(&p)?);
18491×
            } else {
18501×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18511×
            }
1852
        }
18530×
        ProposalCmd::Edit { number, title, body, body_file } => {
18540×
            let body = match (&body, &body_file) {
18550×
                (None, None) => None,
18560×
                _ => Some(body_of(body, body_file)?),
1857
            };
18580×
            if title.is_none() && body.is_none() {
18590×
                bail!("say what to change: --title, --body or --body-file");
18600×
            }
18610×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
18620×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18630×
            if json {
18640×
                println!("{}", serde_json::to_string(&p)?);
18650×
            } else {
18660×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18670×
            }
1868
        }
18690×
        ProposalCmd::Label(change) => {
18700×
            let path = format!("{base}/proposals/{}", change.number);
18710×
            let now: Proposal = c.get(&path)?;
18720×
            let labels = change.apply(&now.labels)?;
18730×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
18740×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
18750×
            if json {
18760×
                println!("{}", serde_json::to_string(&p)?);
18770×
            } else {
18780×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
18790×
            }
1880
        }
18810×
        ProposalCmd::Comment { number, body, body_file } => {
18820×
            let body = body_of(body, body_file)?;
18830×
            if body.trim().is_empty() {
18840×
                bail!("give the comment with --body or --body-file");
18850×
            }
18860×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18870×
            println!("{} commented on #{number}", ui::ok("✔"));
1888
        }
18890×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
18900×
            let path = format!("{base}/proposals/{number}/auto-land");
18910×
            let p: Proposal =
18920×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
18930×
            if json {
18940×
                println!("{}", serde_json::to_string(&p)?);
18950×
            } else if p.landed.is_some() {
18960×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
18970×
            } else if p.auto_land.is_some() {
18980×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
18990×
            } else {
19000×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
19010×
            }
1902
        }
19032×
        ProposalCmd::Land { number, over_checks, .. } => {
19042×
            let body = match &over_checks {
19050×
                Some(r) => serde_json::json!({ "over_checks": r }),
19062×
                None => serde_json::json!({}),
1907
            };
19082×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
19091×
            if json {
19100×
                println!("{}", serde_json::to_string(&p)?);
19111×
            } else {
19121×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
19131×
            }
1914
        }
19150×
        ProposalCmd::Close { number, message } => {
19160×
            if let Some(body) = message {
19170×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
19180×
            }
19190×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
19200×
            if json {
19210×
                println!("{}", serde_json::to_string(&p)?);
19220×
            } else {
19230×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
19240×
            }
1925
        }
19260×
        ProposalCmd::Reopen { number } => {
19270×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
19280×
            if json {
19290×
                println!("{}", serde_json::to_string(&p)?);
19300×
            } else {
19310×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
19320×
            }
1933
        }
19340×
        ProposalCmd::Ready { number, undo } => {
19350×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
19360×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
19370×
            if json {
19380×
                println!("{}", serde_json::to_string(&p)?);
19390×
            } else if undo {
19400×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
19410×
            } else {
19420×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
19430×
            }
1944
        }
19450×
        ProposalCmd::Checks { number } => {
19460×
            let path = format!("{base}/proposals/{number}/checks");
19470×
            if json {
19480×
                println!("{}", c.get_text(&path)?);
19490×
                return Ok(0);
19500×
            }
19510×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
19520×
            if checks.is_empty() {
19530×
                println!("{}", ui::dim("No checks yet."));
19540×
            }
19550×
            for ch in checks {
19560×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
19570×
            }
1958
        }
1959
    }
19603×
    Ok(0)
19614×
}
1962
19631×
fn run_line(r: &FlowRun) -> String {
19641×
    let what =
19651×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
19661×
    format!(
1967
        "{} {} {} {}",
19681×
        ui::status(&r.status),
19691×
        ui::dim(&format!("#{}", r.number)),
1970
        what,
19711×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1972
    )
19731×
}
1974
19751×
fn print_run(r: &FlowRun, timings: bool) {
19761×
    println!("{}", run_line(r));
19771×
    for j in &r.jobs {
19781×
        let dur = match (j.started_ms, j.finished_ms) {
19790×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
19801×
            _ => String::new(),
1981
        };
19821×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
19831×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1984
        // Why a queued job no runner can take waits (oxygenhub#28), and
1985
        // why a job ran where it did (oxygenflow#42).
19861×
        if j.status == "queued" && !j.waiting.is_empty() {
19870×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
19881×
        } else if !j.placed.is_empty() {
19890×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
19901×
        }
19911×
        if timings {
19920×
            let t = timing_line(j);
19930×
            if !t.is_empty() {
19940×
                println!("    {}", ui::dim(&t));
19950×
            }
19961×
        }
1997
    }
19981×
    if !r.error.is_empty() {
19990×
        println!("{}", ui::bad(&r.error));
20001×
    }
20011×
    println!("{}", ui::dim(&r.url));
20021×
}
2003
2004
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
20053×
fn took(ms: i64) -> String {
20063×
    match ms {
20073×
        ..=999 => format!("{ms} ms"),
20082×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
20091×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
2010
    }
20113×
}
2012
2013
/// MiB as a person reads them.
20142×
fn mib(m: i64) -> String {
20152×
    if m >= 1024 {
20161×
        format!("{:.1} GiB", m as f64 / 1024.0)
2017
    } else {
20181×
        format!("{m} MiB")
2019
    }
20202×
}
2021
2022
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
2023
/// phase its runner reported, and the most disk and memory it took.
20242×
fn timing_line(j: &FlowJob) -> String {
20252×
    let mut parts = vec![];
20262×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
20271×
        parts.push(format!("waited {}", took((s - q).max(0))));
20281×
    }
20292×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
20302×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
20312×
        .into_iter()
20324×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
20332×
        .collect();
20342×
    if !peaks.is_empty() {
20351×
        parts.push(format!("peak {}", peaks.join(", ")));
20361×
    }
20372×
    parts.join(" · ")
20382×
}
2039
2040
/// A report's path, its segments encoded and its slashes kept.
20411×
fn enc_path(path: &str) -> String {
20421×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
20431×
}
2044
2045
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
2046
/// files are at `files(path)`. By default its report.toml; with `list`
2047
/// what it holds; with `file` one file, to stdout or `output`.
20480×
fn show_report(
20490×
    c: &Client,
20500×
    at: &str,
20510×
    files: impl Fn(&str) -> String,
20520×
    list: bool,
20530×
    file: Option<String>,
20540×
    output: Option<std::path::PathBuf>,
20550×
    json: bool,
20560×
) -> Result<()> {
2057
    use std::io::Write;
20580×
    if let Some(path) = file {
20590×
        let bytes = c.get_bytes(&files(&path))?;
20600×
        match output {
20610×
            Some(out) => {
20620×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
20630×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
2064
            }
20650×
            None => std::io::stdout().write_all(&bytes)?,
2066
        }
20670×
        return Ok(());
20680×
    }
20690×
    if json {
20700×
        println!("{}", c.get_text(at)?);
20710×
        return Ok(());
20720×
    }
20730×
    if !list {
20740×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
20750×
        return Ok(());
20760×
    }
20770×
    let r: Report = c.get(at)?;
20780×
    print_report(&r);
20790×
    if r.files_expired_ms.is_some() {
20800×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
20810×
    }
20820×
    for f in &r.manifest {
20830×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
20840×
    }
20850×
    println!("{}", ui::dim(&r.url));
20860×
    Ok(())
20870×
}
2088
2089
/// A report's heading, metrics and context.
20900×
fn print_report(r: &Report) {
20910×
    let from = match r.run {
20920×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
20930×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2094
    };
20950×
    println!(
2096
        "{} {} {}",
20970×
        ui::strong(&r.name),
20980×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
20990×
        ui::dim(&format!("· {from} · {} files", r.files))
2100
    );
21010×
    if !r.summary.is_empty() {
21020×
        println!("  {}", r.summary);
21030×
    }
21040×
    for m in &r.metrics {
21050×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
21060×
        let mut notes = vec![];
21070×
        if !m.better.is_empty() {
21080×
            notes.push(format!("{} is better", m.better));
21090×
        }
21100×
        if let Some(a) = m.fail_above {
21110×
            notes.push(format!("fails above {a}"));
21120×
        }
21130×
        if let Some(b) = m.fail_below {
21140×
            notes.push(format!("fails below {b}"));
21150×
        }
21160×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
21170×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2118
    }
21190×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
21200×
        let line: Vec<String> =
21210×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
21220×
        println!("  {}", ui::dim(&line.join(" ")));
21230×
    }
21240×
}
2125
2126
/// `oh report …` (oxygenhub#348).
21270×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
21280×
    let base = t.repo_path()?;
21290×
    match cmd {
21300×
        ReportCmd::List { bookmark } => {
21310×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
21320×
            if json {
21330×
                println!("{}", c.get_text(&path)?);
21340×
                return Ok(0);
21350×
            }
21360×
            let list: Vec<Report> = c.get(&path)?;
21370×
            if list.is_empty() {
21380×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
21390×
            }
21400×
            for r in &list {
21410×
                print_report(r);
21420×
            }
2143
        }
21440×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
21450×
            let at = format!("{base}/reports/{}", enc(&report));
21460×
            let query = match (id, bookmark) {
21470×
                (Some(id), _) => format!("?id={id}"),
21480×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
21490×
                (None, None) => String::new(),
2150
            };
21510×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
21520×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2153
        }
2154
    }
21550×
    Ok(0)
21560×
}
2157
21580×
fn live(status: &str) -> bool {
21590×
    matches!(status, "queued" | "running")
21600×
}
2161
2162
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
21630×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
21640×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
21650×
    if json {
21660×
        println!("{done}");
21670×
    } else {
21680×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
21690×
    }
21700×
    Ok(())
21710×
}
2172
21730×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
21740×
    let path = format!("{base}/flow/runs/{number}");
21750×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2176
    loop {
21770×
        let r: FlowRun = c.get(&path)?;
21780×
        if !json {
21790×
            for j in &r.jobs {
21800×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
21810×
                if seen.get(&j.name) != Some(&shown) {
21820×
                    println!("{} {}", ui::status(&j.status), j.name);
21830×
                    if j.status == "queued" && !j.waiting.is_empty() {
21840×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
21850×
                    }
21860×
                    seen.insert(j.name.clone(), shown);
21870×
                }
2188
            }
21890×
        }
21900×
        if !live(&r.status) {
21910×
            if json {
21920×
                println!("{}", serde_json::to_string(&r)?);
21930×
            } else {
21940×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
21950×
            }
21960×
            return Ok(if r.status == "passed" { 0 } else { 1 });
21970×
        }
21980×
        std::thread::sleep(Duration::from_secs(3));
2199
    }
22000×
}
2201
22023×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
22033×
    let base = t.repo_path()?;
22040×
    match cmd {
22051×
        RunCmd::List { limit } => {
22061×
            let path = format!("{base}/flow/runs?limit={limit}");
22071×
            if json {
22081×
                println!("{}", c.get_text(&path)?);
22091×
                return Ok(0);
22100×
            }
22110×
            let runs: Vec<FlowRun> = c.get(&path)?;
22120×
            if runs.is_empty() {
22130×
                println!("{}", ui::dim("No runs yet."));
22140×
            }
22150×
            for r in &runs {
22160×
                println!("{}", run_line(r));
22170×
            }
2218
        }
22191×
        RunCmd::View { number, bookmark, timings } => {
22201×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
22211×
            let path = format!("{base}/flow/runs/{number}");
22221×
            if json {
22230×
                println!("{}", c.get_text(&path)?);
22240×
                return Ok(0);
22251×
            }
22261×
            print_run(&c.get(&path)?, timings);
2227
        }
22281×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
22291×
            let mut body = match (bookmark, change) {
22300×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
22310×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
22321×
                (None, None) => serde_json::json!({}),
2233
            };
22341×
            if !jobs.is_empty() {
22350×
                body["jobs"] = serde_json::json!(jobs);
22361×
            }
22371×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
22381×
            let n = started["number"].as_i64().context("the hub named no run")?;
22391×
            if !json || !follow {
22401×
                if json {
22410×
                    println!("{started}");
22421×
                } else {
22431×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
22441×
                }
22450×
            }
22461×
            if follow {
22470×
                return watch(c, &base, n, json);
22481×
            }
2249
        }
22500×
        RunCmd::Watch { number, bookmark } => {
22510×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
22520×
            return watch(c, &base, number, json);
2253
        }
22540×
        RunCmd::Log { number, job } => {
22550×
            let mut after = 0;
2256
            loop {
22570×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
22580×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
22590×
                if lines.is_empty() {
22600×
                    break;
22610×
                }
22620×
                for l in &lines {
22630×
                    if json {
22640×
                        println!("{}", serde_json::to_string(l)?);
22650×
                    } else if l.stream == "flow" {
22660×
                        println!("{}", ui::dim(&l.text));
22670×
                    } else {
22680×
                        println!("{}", l.text);
22690×
                    }
2270
                }
22710×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2272
            }
2273
        }
22740×
        RunCmd::Report { number, job, pick } => {
22750×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
22760×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
22770×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
22780×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2279
        }
22800×
        RunCmd::Rerun { number, job: Some(job) } => {
22810×
            let queued: serde_json::Value =
22820×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
22830×
            if json {
22840×
                println!("{queued}");
22850×
            } else {
22860×
                let n = queued["queued"].as_i64().unwrap_or(1);
22870×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
22880×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2289
            }
2290
        }
22910×
        RunCmd::Rerun { number, job: None } => {
22920×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
22930×
            if json {
22940×
                println!("{started}");
22950×
            } else {
22960×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
22970×
            }
2298
        }
22990×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
23000×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
23010×
        RunCmd::Cancel { number } => {
23020×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
23030×
            if json {
23040×
                println!("{done}");
23050×
            } else {
23060×
                println!("{} cancelled run #{number}", ui::ok("✔"));
23070×
            }
2308
        }
2309
    }
23102×
    Ok(0)
23113×
}
2312
23130×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
23140×
    let base = t.repo_path()?;
23150×
    match cmd {
2316
        LabelCmd::List => {
23170×
            let path = format!("{base}/labels");
23180×
            if json {
23190×
                println!("{}", c.get_text(&path)?);
23200×
                return Ok(0);
23210×
            }
23220×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
23230×
            if labels.is_empty() {
23240×
                println!("{}", ui::dim("No labels."));
23250×
            }
23260×
            for l in labels {
23270×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
23280×
            }
2329
        }
23300×
        LabelCmd::Create { name, colour, description } => {
23310×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
23320×
            if json {
23330×
                println!("{}", serde_json::to_string(&l)?);
23340×
            } else {
23350×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
23360×
            }
2337
        }
23380×
        LabelCmd::Delete { name } => {
23390×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
23400×
            println!("{} deleted label {name}", ui::ok("✔"));
2341
        }
2342
    }
23430×
    Ok(0)
23440×
}
2345
23460×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
23470×
    let base = match (&org, site) {
23480×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
23490×
        (None, true) => "/admin/assistants".to_string(),
23500×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2351
    };
23520×
    match cmd {
2353
        AssistantCmd::List => {
23540×
            if json {
23550×
                println!("{}", c.get_text(&base)?);
23560×
                return Ok(0);
23570×
            }
23580×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
23590×
            if list.is_empty() {
23600×
                println!("{}", ui::dim("No assistants."));
23610×
            }
23620×
            for a in list {
23630×
                let state = if a.enabled && !a.off_above {
23640×
                    ui::ok("on")
23650×
                } else if a.off_above {
23660×
                    ui::dim("off above")
2367
                } else {
23680×
                    ui::dim("off")
2369
                };
23700×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
23710×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2372
            }
2373
        }
23740×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
23750×
            let token = match token_env {
23760×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
23770×
                None => String::new(),
2378
            };
23790×
            let body =
23800×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
23810×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
23820×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2383
        }
23840×
        AssistantCmd::Remove { name } => {
23850×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
23860×
            println!("{} removed {name}", ui::ok("✔"));
2387
        }
23880×
        AssistantCmd::Prompt { set } => {
23890×
            let p: hub_api::AssistantPrompt = match set {
23900×
                Some(path) => {
23910×
                    let text = if path.as_os_str() == "-" {
23920×
                        let mut s = String::new();
23930×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
23940×
                        s
2395
                    } else {
23960×
                        std::fs::read_to_string(&path)?
2397
                    };
23980×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2399
                }
24000×
                None => c.get(&format!("{base}/prompt"))?,
2401
            };
24020×
            if json {
24030×
                println!("{}", serde_json::to_string(&p)?);
24040×
                return Ok(0);
24050×
            }
24060×
            for (from, text) in &p.inherited {
24070×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
24080×
            }
24090×
            if p.prompt.is_empty() {
24100×
                println!("{}", ui::dim("No prompt of its own."));
24110×
            } else {
24120×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
24130×
            }
2414
        }
2415
    }
24160×
    Ok(0)
24170×
}
2418
24192×
fn project_line(p: &hub_api::Project) -> String {
24202×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
24212×
    let private = if p.public { "" } else { " · private" };
24222×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
24232×
}
2424
242510×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
242610×
    let owner = match owner {
24270×
        Some(o) => o,
242810×
        None => t.repo()?.0.to_string(),
2429
    };
243010×
    let base = format!("/projects/{}", enc(&owner));
243110×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
24321×
        let p: hub_api::Project =
24331×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
24341×
        if json {
24350×
            println!("{}", serde_json::to_string(&p)?);
24361×
        } else {
24371×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
24381×
        }
24391×
        Ok(())
24401×
    };
24414×
    match cmd {
2442
        ProjectCmd::List => {
24431×
            if json {
24440×
                println!("{}", c.get_text(&base)?);
24450×
                return Ok(0);
24461×
            }
24471×
            let list: Vec<hub_api::Project> = c.get(&base)?;
24481×
            if list.is_empty() {
24490×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
24501×
            }
24511×
            for p in &list {
24521×
                println!("{}", project_line(p));
24531×
            }
2454
        }
24553×
        ProjectCmd::View { number, archived, filter, view } => {
24563×
            let cards = format!("{base}/{number}/cards?archived=true");
24573×
            let path = match (&filter, &view) {
24580×
                (Some(q), _) => format!("{base}/{number}?q={}", enc(q)),
24590×
                (None, Some(v)) => format!("{base}/{number}?view={}", enc(v)),
24603×
                (None, None) => format!("{base}/{number}"),
2461
            };
24623×
            if json {
24632×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
24642×
                return Ok(0);
24651×
            }
24661×
            let mut b: hub_api::Board = c.get(&path)?;
24671×
            if archived {
24680×
                b.columns = c.get(&cards)?;
24691×
            }
24701×
            println!("{}", project_line(&b.project));
24711×
            if !b.project.description.is_empty() {
24721×
                println!("{}", b.project.description);
24731×
            }
24741×
            if !b.filter.is_empty() {
24750×
                println!("{}", ui::dim(&format!("filter: {}", b.filter)));
24761×
            }
24771×
            if !b.views.is_empty() && filter.is_none() && view.is_none() {
24780×
                let names: Vec<&str> = b.views.iter().map(|v| v.name.as_str()).collect();
24790×
                println!("{}", ui::dim(&format!("views: {} (oh project view {number} --view NAME)", names.join(", "))));
24801×
            }
24813×
            for col in &b.columns {
24823×
                println!();
24833×
                let wip = match col.wip_limit {
24840×
                    Some(w) if col.cards.len() as i64 > w => format!(" · over its limit of {w}"),
24850×
                    Some(w) => format!(" · limit {w}"),
24863×
                    None => String::new(),
2487
                };
24883×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}{wip}", col.cards.len(), col.id)));
24893×
                if col.cards.is_empty() {
24901×
                    println!("  {}", ui::dim("(empty)"));
24912×
                }
24923×
                for card in &col.cards {
24932×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
24942×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
24952×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
24962×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
24972×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
24982×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2499
                }
2500
            }
25011×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2502
        }
25031×
        ProjectCmd::Create { title, description, private } => {
25041×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
25051×
            if json {
25060×
                println!("{}", serde_json::to_string(&p)?);
25071×
            } else {
25081×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
25091×
            }
2510
        }
25110×
        ProjectCmd::Charts { number, filter } => {
25120×
            let path = match &filter {
25130×
                Some(q) => format!("{base}/{number}/charts?q={}", enc(q)),
25140×
                None => format!("{base}/{number}/charts"),
2515
            };
25160×
            if json {
25170×
                println!("{}", c.get_text(&path)?);
25180×
                return Ok(0);
25190×
            }
25200×
            let ch: hub_api::BoardCharts = c.get(&path)?;
25210×
            println!("{}", ui::strong("Forecasts"));
25220×
            for f in &ch.forecasts {
25230×
                let when = match (&f.p50, &f.p85) {
25240×
                    (Some(a), Some(b)) => format!("50% by {a}, 85% by {b}"),
25250×
                    (Some(a), None) => format!("50% by {a}, 85% beyond ten years"),
25260×
                    _ => "no forecast: nothing has reached Done in the weeks it draws from".to_string(),
2527
                };
25280×
                println!("  {}  {} left · {when}", f.scope, f.remaining);
2529
            }
25300×
            if let Some(f) = ch.forecasts.first() {
25310×
                println!("  {}", ui::dim(&format!("from {} week(s) of throughput", f.weeks_of_history)));
25320×
            }
25330×
            println!();
25340×
            match (ch.cycle_time_median_days, ch.cycle_time_p85_days) {
25350×
                (Some(m), Some(p)) => {
25360×
                    println!("{} median {m} d, 85th percentile {p} d over {} finished", ui::strong("Cycle time"), ch.finished)
2537
                }
25380×
                _ => println!("{} {}", ui::strong("Cycle time"), ui::dim("no card has gone from started to Done yet")),
2539
            }
25400×
            let weeks: Vec<String> = ch.throughput.iter().map(|w| w.done.to_string()).collect();
25410×
            println!("{} {} {}", ui::strong("Throughput"), weeks.join(" "), ui::dim("(cards done each week, oldest first)"));
25420×
            if let Some(b) = &ch.burn_down {
25430×
                println!(
25440×
                    "{} {}: {} left of {}",
25450×
                    ui::strong("Burn-down"),
25460×
                    b.iteration,
25470×
                    b.left.last().unwrap_or(&0),
25480×
                    b.scope.last().unwrap_or(&0)
25490×
                );
25500×
            }
2551
        }
25520×
        ProjectCmd::Column { cmd } => {
25530×
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
25540×
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
25550×
                ColumnCmd::Add { number, name } => {
25560×
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
25570×
                    (number, b, format!("added column {name}"))
2558
                }
25590×
                ColumnCmd::Rename { number, column, to } => {
25600×
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
25610×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2562
                }
25630×
                ColumnCmd::Move { number, column, to, left, right } => {
25640×
                    let position = match to {
25650×
                        Some(n) => n - 1,
2566
                        None => {
25670×
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
25680×
                            let at = now
25690×
                                .columns
25700×
                                .iter()
25710×
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
25720×
                                .with_context(|| format!("no column {column} on board {number}"))?
2573
                                as i64;
25740×
                            if left {
25750×
                                (at - 1).max(0)
2576
                            } else {
25770×
                                debug_assert!(right);
25780×
                                at + 1
2579
                            }
2580
                        }
2581
                    };
25820×
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
25830×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2584
                }
25850×
                ColumnCmd::Remove { number, column } => {
25860×
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2587
                }
2588
            };
25890×
            if json {
25900×
                println!("{}", serde_json::to_string(&b)?);
2591
            } else {
25920×
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
25930×
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2594
            }
2595
        }
25961×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
25970×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
25980×
        ProjectCmd::Transfer { number, to } => {
25990×
            let p: hub_api::Project =
26000×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
26010×
            if json {
26020×
                println!("{}", serde_json::to_string(&p)?);
26030×
            } else {
26040×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
26050×
            }
2606
        }
26072×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2608
            // The hub names a card's issue as `repo#N` among the owner's
2609
            // repositories.
26102×
            let reference = match reference {
26111×
                None => String::new(),
26121×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
26130×
                    Some((o, rest)) if o == owner => rest.to_string(),
26140×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
26150×
                    None => r,
2616
                },
26171×
                Some(r) => {
26181×
                    let n = r.trim_start_matches('#');
26191×
                    if n.parse::<i64>().is_err() {
26200×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
26211×
                    }
26221×
                    format!("{}#{n}", t.repo()?.1)
2623
                }
2624
            };
26252×
            let note = note.unwrap_or_default();
26262×
            if reference.is_empty() && note.is_empty() {
26270×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
26282×
            }
26291×
            let card: hub_api::ProjectCard =
26302×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
26311×
            if json {
26320×
                println!("{}", serde_json::to_string(&card)?);
2633
            } else {
26341×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2635
            }
2636
        }
26371×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
26381×
            (Some(card), None) => {
26391×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
26401×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2641
            }
26420×
            (None, Some(from)) => {
26430×
                let r: hub_api::CardsMoved = c.send(
26440×
                    "POST",
26450×
                    &format!("{base}/{number}/cards/move"),
26460×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
26470×
                )?;
26480×
                if json {
26490×
                    println!("{}", serde_json::to_string(&r)?);
26500×
                    return Ok(0);
26510×
                }
26520×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
26530×
                for m in &r.moved {
26540×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2655
                }
26560×
                let verb = if dry_run { "would move" } else { "moved" };
26570×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2658
            }
26590×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2660
        },
26610×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
26620×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
26630×
                None => None,
26640×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2665
            };
26660×
            let r: hub_api::CardsArchived = c.send(
26670×
                "POST",
26680×
                &format!("{base}/{number}/cards/archive"),
26690×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
26700×
            )?;
26710×
            if json {
26720×
                println!("{}", serde_json::to_string(&r)?);
26730×
                return Ok(0);
26740×
            }
26750×
            let verb = if dry_run { "would archive" } else { "archived" };
26760×
            for a in &r.archived {
26770×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
26780×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2679
            }
26800×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2681
        }
26820×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
26830×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
26840×
            println!("{} card {card} restored", ui::ok("✔"));
2685
        }
26861×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
26871×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
26881×
            println!("{} card {card} removed", ui::ok("✔"));
2689
        }
2690
    }
26917×
    Ok(0)
269210×
}
2693
26940×
fn milestone_line(m: &hub_api::Milestone) -> String {
26950×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
26960×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
26970×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
26980×
}
2699
27000×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
27010×
    let base = t.repo_path()?;
27020×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
27030×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
27040×
        if json {
27050×
            println!("{}", serde_json::to_string(&m)?);
27060×
        } else {
27070×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
27080×
        }
27090×
        Ok(())
27100×
    };
27110×
    match cmd {
2712
        MilestoneCmd::List => {
27130×
            let path = format!("{base}/milestones");
27140×
            if json {
27150×
                println!("{}", c.get_text(&path)?);
27160×
                return Ok(0);
27170×
            }
27180×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
27190×
            if list.is_empty() {
27200×
                println!("{}", ui::dim("No milestones."));
27210×
            }
27220×
            for m in &list {
27230×
                println!("{}", milestone_line(m));
27240×
            }
2725
        }
27260×
        MilestoneCmd::Create { title, description, due } => {
27270×
            let m: hub_api::Milestone =
27280×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
27290×
            if json {
27300×
                println!("{}", serde_json::to_string(&m)?);
27310×
            } else {
27320×
                println!("{} milestone {}", ui::ok("✔"), m.title);
27330×
            }
2734
        }
27350×
        MilestoneCmd::Edit { title, rename, description, due } => {
27360×
            if rename.is_none() && description.is_none() && due.is_none() {
27370×
                bail!("say what to change: --rename, --description or --due");
27380×
            }
27390×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2740
        }
27410×
        MilestoneCmd::Close { title } => {
27420×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2743
        }
27440×
        MilestoneCmd::Reopen { title } => {
27450×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2746
        }
2747
    }
27480×
    Ok(0)
27490×
}
2750
27510×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
27520×
    let base = t.repo_path()?;
27530×
    match cmd {
2754
        TagCmd::List => {
27550×
            let path = format!("{base}/tags");
27560×
            if json {
27570×
                println!("{}", c.get_text(&path)?);
27580×
                return Ok(0);
27590×
            }
27600×
            let tags: Vec<Tag> = c.get(&path)?;
27610×
            if tags.is_empty() {
27620×
                println!("{}", ui::dim("no tags"));
27630×
            }
27640×
            for t in tags {
27650×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
27660×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
27670×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2768
            }
2769
        }
27700×
        TagCmd::Create { name, target, message } => {
27710×
            let new = hub_api::NewTag { name, target, message };
27720×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
27730×
            if json {
27740×
                println!("{}", serde_json::to_string(&made)?);
27750×
            } else {
27760×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
27770×
            }
2778
        }
27790×
        TagCmd::Delete { name, reason } => {
27800×
            let reason = reason.unwrap_or_default();
27810×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
27820×
            if json {
27830×
                println!("{}", serde_json::json!({ "withdrawn": name }));
27840×
            } else {
27850×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
27860×
            }
2787
        }
2788
    }
27890×
    Ok(0)
27900×
}
2791
27924×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
27934×
    let base = t.repo_path()?;
27944×
    match cmd {
2795
        ReleaseCmd::List => {
27961×
            let path = format!("{base}/releases");
27971×
            if json {
27981×
                println!("{}", c.get_text(&path)?);
27991×
                return Ok(0);
28000×
            }
28010×
            let list: Vec<Release> = c.get(&path)?;
28020×
            if list.is_empty() {
28030×
                println!("{}", ui::dim("No releases."));
28040×
            }
28050×
            for r in &list {
28060×
                println!(
2807
                    "{} {} {}{}",
28080×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
28090×
                    ui::strong(&r.tag),
2810
                    r.title,
28110×
                    ui::dim(&format!(
2812
                        " · {} asset{} · {}",
28130×
                        r.assets.len(),
28140×
                        if r.assets.len() == 1 { "" } else { "s" },
28150×
                        ui::ago(r.created_ms)
2816
                    ))
2817
                );
2818
            }
2819
        }
28201×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
28211×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
28221×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
28231×
            if json {
28240×
                println!("{}", serde_json::to_string(&r)?);
28251×
            } else {
28261×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
28271×
            }
2828
        }
28290×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
28300×
            let notes = match notes.as_deref() {
28310×
                Some("-") => Some(body_of(None, Some("-".into()))?),
28320×
                _ => notes,
2833
            };
28340×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
28350×
                bail!("say what to change: --title, --notes or --prerelease");
28360×
            }
28370×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
28380×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
28390×
            if json {
28400×
                println!("{}", serde_json::to_string(&r)?);
28410×
            } else {
28420×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
28430×
            }
2844
        }
28451×
        ReleaseCmd::Upload { tag, files } => {
28461×
            if files.is_empty() {
28470×
                bail!("name the files to attach");
28481×
            }
28491×
            for f in files {
28501×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
28511×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
28521×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
28531×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2854
            }
2855
        }
28561×
        ReleaseCmd::Trust { tag } => {
28571×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
28581×
            if json {
28590×
                println!("{}", c.get_text(&path)?);
28600×
                return Ok(0);
28611×
            }
28621×
            let r: serde_json::Value = c.get(&path)?;
28631×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
28641×
            let mut worst = 0;
28654×
            for ch in r["audit"].as_array().into_iter().flatten() {
28664×
                let v = ch["verdict"].as_str().unwrap_or("");
28674×
                worst = worst.max(match v {
28684×
                    "fail" => 2,
28694×
                    "warn" => 1,
28703×
                    _ => 0,
2871
                });
28724×
                let g = match v {
28734×
                    "pass" => ui::ok("✔"),
28741×
                    "warn" => ui::warn("!"),
28750×
                    _ => ui::bad("✘"),
2876
                };
28774×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2878
            }
28791×
            return Ok(if worst == 2 { 1 } else { 0 });
2880
        }
2881
    }
28822×
    Ok(0)
28834×
}
2884
2885
#[cfg(test)]
2886
mod tests {
2887
2888
    #[test]
28891×
    fn job_timings_and_report_commands_read_plainly() {
2890
        use clap::Parser;
28911×
        let job = hub_api::FlowJob {
28921×
            name: "perf".into(),
28931×
            status: "passed".into(),
28941×
            depends_on: vec![],
28951×
            runner: "earth-1".into(),
28961×
            exit_code: Some(0),
28971×
            error: String::new(),
28981×
            started_ms: Some(13_000),
28991×
            finished_ms: Some(200_000),
29001×
            log_lines: 10,
29011×
            waiting: String::new(),
29021×
            placed: String::new(),
29031×
            approval: String::new(),
29041×
            queued_ms: Some(1_000),
29051×
            ready_ms: Some(12_500),
29061×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
29071×
            peak_disk_mib: Some(2150),
29081×
            peak_memory_mib: Some(900),
29091×
        };
29101×
        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");
29111×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
29121×
        assert_eq!(super::timing_line(&bare), "");
29131×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2914
29151×
        let cli =
29161×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
29171×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
29181×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
29191×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
29201×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
29211×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
29221×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
29231×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
29241×
    }
2925
2926
    #[test]
29271×
    fn runner_update_scopes_resolve_by_name_or_id() {
29281×
        let all = hub_api::RunnerUpdates {
29291×
            repo: String::new(),
29301×
            settings: vec![],
29311×
            groups: vec![hub_api::RunnerGroup {
29321×
                id: 4,
29331×
                owner: "acme".into(),
29341×
                name: "canary".into(),
29351×
                percent: None,
29361×
                members: vec![],
29371×
                wave: None,
29381×
            }],
29391×
            runners: vec![],
29401×
            holds: vec![],
29411×
        };
29421×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
29431×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
29443×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
29453×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2946
        }
29471×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
29481×
        assert!(update_scope("everyone", &all).is_err());
29491×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
29501×
        assert!(switch(Some("yes")).is_err());
29511×
    }
2952
    use super::*;
2953
2954
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2955
    /// help says, and a drop is named by its id or its address.
2956
    #[test]
29571×
    fn drop_commands_parse() {
29581×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
29591×
        match cli.cmd {
29601×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
29611×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
29621×
                assert!(secret);
29631×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2964
            }
29650×
            _ => panic!("not drop create"),
2966
        }
29671×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
29681×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
29691×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
29701×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
29711×
                assert!(channel.is_none() && dry_run.is_none());
2972
            }
29730×
            _ => panic!("not runner-updates set"),
2974
        }
29751×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
29761×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
29771×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
29780×
            _ => panic!("not drop list"),
2979
        }
29801×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
29811×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
29821×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2983
            }
29840×
            _ => panic!("not drop view"),
2985
        }
29861×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
29874×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
29884×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2989
        }
29901×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
29911×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
29921×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
29930×
            _ => panic!("not drop comment"),
2994
        }
29951×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
29961×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
29971×
        assert!(drop_id("andy/notes").is_err());
29981×
    }
2999
}