OXYGENHUB

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

672 of 1760 lines run, 49 of 265 functions · run #545 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
        /// Switch OxygenFlow on: `on` (the site's runners; site administrators) or `own` (the owner's runners)
317
        #[arg(long)]
318
        flow: Option<String>,
319
        /// Start its wiki with a Home page
320
        #[arg(long)]
321
        wiki: bool,
322
        /// Its default bookmark (default: the owner's, else the site's, else main)
323
        #[arg(long, short = 'B')]
324
        bookmark: Option<String>,
325
    },
326
}
327
328
#[derive(Subcommand)]
329
enum IssueCmd {
330
    /// Put labels on an issue or take them off (triage)
331
    Label(LabelChange),
332
    /// Open issues (or --state closed|all)
333
    List {
334
        #[arg(long, default_value = "open")]
335
        state: String,
336
    },
337
    /// One issue with its comments
338
    View { number: i64 },
339
    /// Open an issue
340
    Create {
341
        #[arg(long, short)]
342
        title: String,
343
        #[arg(long, short)]
344
        body: Option<String>,
345
        /// Read the body from a file ("-" for stdin)
346
        #[arg(long, short = 'F')]
347
        body_file: Option<String>,
348
        /// A label (repeatable)
349
        #[arg(long, short)]
350
        label: Vec<String>,
351
        /// Also put it on this board of the repository's owner
352
        #[arg(long, short)]
353
        project: Option<i64>,
354
        /// The board's column for it, by name (default: the first)
355
        #[arg(long, requires = "project")]
356
        column: Option<String>,
357
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
358
        #[arg(long, short = 'a', value_name = "FILE")]
359
        attach: Vec<std::path::PathBuf>,
360
    },
361
    /// Close an issue, with an optional comment saying why
362
    Close {
363
        number: i64,
364
        /// `completed` or `not_planned`
365
        #[arg(long, default_value = "completed")]
366
        reason: String,
367
        #[command(flatten)]
368
        comment: StateComment,
369
    },
370
    /// Reopen an issue, with an optional comment saying why
371
    Reopen {
372
        number: i64,
373
        #[command(flatten)]
374
        comment: StateComment,
375
    },
376
    /// Change an issue's title or body (its author or triage), or its
377
    /// labels, assignees or milestone as whole sets (triage)
378
    Edit {
379
        number: i64,
380
        #[arg(long, short)]
381
        title: Option<String>,
382
        #[arg(long, short)]
383
        body: Option<String>,
384
        /// Read the body from a file ("-" for stdin)
385
        #[arg(long, short = 'F', conflicts_with = "body")]
386
        body_file: Option<String>,
387
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
388
        #[arg(long, short)]
389
        label: Vec<String>,
390
        /// Clear its labels
391
        #[arg(long, conflicts_with = "label")]
392
        no_labels: bool,
393
        /// The users it should be assigned to (repeatable)
394
        #[arg(long, short)]
395
        assignee: Vec<String>,
396
        /// Take everyone off it
397
        #[arg(long, conflicts_with = "assignee")]
398
        no_assignees: bool,
399
        /// A milestone's title ("" takes it out of its milestone)
400
        #[arg(long, short)]
401
        milestone: Option<String>,
402
    },
403
    /// Comment on an issue
404
    Comment {
405
        number: i64,
406
        #[arg(long, short)]
407
        body: Option<String>,
408
        /// Read the body from a file ("-" for stdin), as proposal comment
409
        /// does (#260)
410
        #[arg(long, short = 'F', conflicts_with = "body")]
411
        body_file: Option<String>,
412
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
413
        #[arg(long, short = 'a', value_name = "FILE")]
414
        attach: Vec<std::path::PathBuf>,
415
    },
416
}
417
418
#[derive(Subcommand)]
419
enum ProposalCmd {
420
    /// Open proposals (or --state draft|landed|closed|all), newest first
421
    List {
422
        #[arg(long, default_value = "open")]
423
        state: String,
424
        /// At most this many
425
        #[arg(long, default_value_t = 30)]
426
        limit: usize,
427
    },
428
    /// One proposal: its changes, approvals and whether it can land
429
    View { number: i64 },
430
    /// Propose a bookmark's changes for another bookmark
431
    Create {
432
        #[arg(long, short)]
433
        title: String,
434
        #[arg(long, short)]
435
        body: Option<String>,
436
        /// Read the body from a file ("-" for stdin)
437
        #[arg(long, short = 'F', conflicts_with = "body")]
438
        body_file: Option<String>,
439
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
440
        #[arg(long)]
441
        from: String,
442
        /// The bookmark to land them on (default: the repository's default bookmark)
443
        #[arg(long)]
444
        into: Option<String>,
445
        #[arg(long)]
446
        draft: bool,
447
    },
448
    /// Change a proposal's title or description (its author or a maintainer)
449
    Edit {
450
        number: i64,
451
        #[arg(long, short)]
452
        title: Option<String>,
453
        #[arg(long, short)]
454
        body: Option<String>,
455
        /// Read the body from a file ("-" for stdin)
456
        #[arg(long, short = 'F', conflicts_with = "body")]
457
        body_file: Option<String>,
458
    },
459
    /// Put labels on a proposal or take them off (triage)
460
    Label(LabelChange),
461
    /// Comment on a proposal's conversation
462
    Comment {
463
        number: i64,
464
        #[arg(long, short)]
465
        body: Option<String>,
466
        /// Read the comment from a file ("-" for stdin)
467
        #[arg(long, short = 'F', conflicts_with = "body")]
468
        body_file: Option<String>,
469
    },
470
    /// The checks on a proposal's projected state
471
    Checks { number: i64 },
472
    /// Land a proposal on its target, as the page's Land button does
473
    Land {
474
        number: i64,
475
        /// Land before its required checks pass, saying why (maintainers;
476
        /// recorded and audited, #261)
477
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
478
        over_checks: Option<String>,
479
        /// Land it by itself once its checks pass (#261); with --off, don't
480
        #[arg(long)]
481
        when_ready: bool,
482
        /// With --when-ready: turn it off
483
        #[arg(long, requires = "when_ready")]
484
        off: bool,
485
    },
486
    /// Close a proposal without landing it, with an optional comment
487
    Close {
488
        number: i64,
489
        /// Say why, as a comment before it closes
490
        #[arg(long, short = 'm')]
491
        message: Option<String>,
492
    },
493
    /// Reopen a closed proposal
494
    Reopen { number: i64 },
495
    /// Take a draft proposal out of draft, ready for review (its author or triage)
496
    Ready {
497
        number: i64,
498
        /// Turn an open proposal back into a draft instead
499
        #[arg(long)]
500
        undo: bool,
501
    },
502
}
503
504
#[derive(Subcommand)]
505
enum AssistantCmd {
506
    /// The assistants this level sees, its own and those inherited
507
    List,
508
    /// Add an assistant, or change the one of that name
509
    Add {
510
        /// How it shows on reviews (default: the provider's name)
511
        #[arg(long, default_value = "")]
512
        name: String,
513
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
514
        #[arg(long, default_value = "")]
515
        preset: String,
516
        /// The endpoint, when no preset or another one
517
        #[arg(long, default_value = "")]
518
        endpoint: String,
519
        /// chat-completions or anthropic-messages
520
        #[arg(long, default_value = "")]
521
        api: String,
522
        /// One the endpoint lists (`oh assistant models` shows them)
523
        #[arg(long)]
524
        model: String,
525
        /// The API key, read from this environment variable (never typed on the command line)
526
        #[arg(long, value_name = "VAR")]
527
        token_env: Option<String>,
528
        /// Add it turned off
529
        #[arg(long)]
530
        off: bool,
531
    },
532
    /// Remove this level's assistant of that name
533
    Remove { name: String },
534
    /// Show this level's prompt, and those it inherits
535
    Prompt {
536
        /// Set it from this file (`-` for standard input; an empty file clears it)
537
        #[arg(long, value_name = "FILE")]
538
        set: Option<std::path::PathBuf>,
539
    },
540
}
541
542
#[derive(Subcommand)]
543
enum LabelCmd {
544
    /// The repository's labels
545
    List,
546
    /// Create a label, or change the one of that name (triage)
547
    Create {
548
        name: String,
549
        /// `#rrggbb` (default: one the hub picks)
550
        #[arg(long)]
551
        colour: Option<String>,
552
        #[arg(long, short, default_value = "")]
553
        description: String,
554
    },
555
    /// Delete a label, taking it off every issue and proposal (triage)
556
    Delete { name: String },
557
}
558
559
#[derive(Subcommand)]
560
enum ProjectCmd {
561
    /// The owner's boards
562
    List,
563
    /// One board: its columns and cards
564
    View {
565
        number: i64,
566
        /// Its archived cards instead (#293)
567
        #[arg(long)]
568
        archived: bool,
569
        /// Only the cards this filter keeps, as the board's filter bar takes it:
570
        /// words, repo:, assignee:, label:, milestone:, is:open|closed, age:>14d (#361)
571
        #[arg(long, short = 'q', conflicts_with = "view")]
572
        filter: Option<String>,
573
        /// A saved view of the board, by name: its filter (#361)
574
        #[arg(long)]
575
        view: Option<String>,
576
    },
577
    /// Create a board (owner, or an organisation's members)
578
    Create {
579
        title: String,
580
        #[arg(long, short, default_value = "")]
581
        description: String,
582
        /// Only the owner (or the organisation's members) can see it
583
        #[arg(long)]
584
        private: bool,
585
    },
586
    /// Close a board
587
    Close { number: i64 },
588
    /// Reopen a board
589
    Reopen { number: i64 },
590
    /// Move a board to another owner you may make boards under (an
591
    /// organisation, say); it takes the next number there
592
    Transfer {
593
        number: i64,
594
        /// The new owner
595
        #[arg(long)]
596
        to: String,
597
    },
598
    /// Cards on a board: add, move, archive, restore, remove
599
    Card {
600
        #[command(subcommand)]
601
        cmd: CardCmd,
602
    },
603
    /// A board's charts from its own history: forecasts, cycle time,
604
    /// throughput (#357)
605
    Charts {
606
        /// The board
607
        number: i64,
608
        /// Forecast only the cards this filter keeps (words, repo:, label:, milestone:…)
609
        #[arg(long, short = 'q')]
610
        filter: Option<String>,
611
    },
612
    /// A board's columns: add, rename, move, remove (#366)
613
    Column {
614
        #[command(subcommand)]
615
        cmd: ColumnCmd,
616
    },
617
}
618
619
#[derive(Subcommand)]
620
enum ColumnCmd {
621
    /// Add a column at the right
622
    Add {
623
        /// The board
624
        number: i64,
625
        name: String,
626
    },
627
    /// Rename a column (by name or id)
628
    Rename {
629
        /// The board
630
        number: i64,
631
        column: String,
632
        /// Its new name
633
        to: String,
634
    },
635
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
636
    Move {
637
        /// The board
638
        number: i64,
639
        column: String,
640
        /// Its place, counting from 1 at the left
641
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
642
        to: Option<i64>,
643
        /// One place to the left
644
        #[arg(long, conflicts_with = "right")]
645
        left: bool,
646
        /// One place to the right
647
        #[arg(long)]
648
        right: bool,
649
    },
650
    /// Remove a column; its cards go to the first remaining one
651
    Remove {
652
        /// The board
653
        number: i64,
654
        column: String,
655
    },
656
}
657
658
#[derive(Subcommand)]
659
enum CardCmd {
660
    /// Put an issue or proposal on a board (`12` or `#12` in this
661
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
662
    /// or a note with --note
663
    Add {
664
        number: i64,
665
        /// The issue or proposal; a number means this repository's
666
        reference: Option<String>,
667
        /// A note card instead
668
        #[arg(long, conflicts_with = "reference")]
669
        note: Option<String>,
670
        /// The column, by name or id (default: the first)
671
        #[arg(long, short)]
672
        column: Option<String>,
673
    },
674
    /// Move a card to another column (by name or id), or with --from every
675
    /// card of a column at once
676
    Move {
677
        number: i64,
678
        /// The card (its id); leave it out with --from
679
        card: Option<i64>,
680
        #[arg(long, short)]
681
        column: String,
682
        /// Move every card of this column (#289)
683
        #[arg(long, conflicts_with = "card")]
684
        from: Option<String>,
685
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
686
        #[arg(long, value_delimiter = ',', requires = "from")]
687
        except: Vec<String>,
688
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
689
        #[arg(long, value_delimiter = ',', requires = "from")]
690
        state: Vec<String>,
691
        /// With --from: say what would move, and move nothing
692
        #[arg(long, requires = "from")]
693
        dry_run: bool,
694
    },
695
    /// Archive a column's cards: off the board, kept and restorable (#293)
696
    Archive {
697
        number: i64,
698
        /// The column, by name or id
699
        #[arg(long)]
700
        from: String,
701
        /// Only cards that joined the column more than this long ago (14d, or 14)
702
        #[arg(long)]
703
        older: Option<String>,
704
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
705
        #[arg(long, value_delimiter = ',')]
706
        except: Vec<String>,
707
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
708
        #[arg(long, value_delimiter = ',')]
709
        state: Vec<String>,
710
        /// Say what would be archived, and archive nothing
711
        #[arg(long)]
712
        dry_run: bool,
713
    },
714
    /// Put an archived card back at the end of its column
715
    Restore { number: i64, card: i64 },
716
    /// Take a card off a board
717
    Remove { number: i64, card: i64 },
718
}
719
720
#[derive(Subcommand)]
721
enum MilestoneCmd {
722
    /// The repository's milestones
723
    List,
724
    /// Create a milestone, or change the one of that title (triage)
725
    Create {
726
        title: String,
727
        #[arg(long, short, default_value = "")]
728
        description: String,
729
        /// Due date, YYYY-MM-DD
730
        #[arg(long)]
731
        due: Option<String>,
732
    },
733
    /// Change a milestone's title, description or due date (triage)
734
    Edit {
735
        title: String,
736
        #[arg(long, short)]
737
        rename: Option<String>,
738
        #[arg(long, short)]
739
        description: Option<String>,
740
        /// Due date, YYYY-MM-DD ("" for none)
741
        #[arg(long)]
742
        due: Option<String>,
743
    },
744
    /// Close a milestone
745
    Close { title: String },
746
    /// Reopen a milestone
747
    Reopen { title: String },
748
}
749
750
/// Labels to put on or take off an issue or proposal.
751
#[derive(clap::Args)]
752
struct LabelChange {
753
    number: i64,
754
    /// A label to add (repeatable)
755
    #[arg(long, short)]
756
    add: Vec<String>,
757
    /// A label to take off (repeatable)
758
    #[arg(long, short)]
759
    remove: Vec<String>,
760
}
761
762
impl LabelChange {
763
    /// The set after the change, from the one there now.
7640×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
7650×
        if self.add.is_empty() && self.remove.is_empty() {
7660×
            bail!("say what to change: --add NAME or --remove NAME");
7670×
        }
7680×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
7690×
        for a in &self.add {
7700×
            if !names.contains(a) {
7710×
                names.push(a.clone());
7720×
            }
773
        }
7740×
        Ok(names)
7750×
    }
776
}
777
7780×
fn label_names(labels: &[String]) -> String {
7790×
    if labels.is_empty() {
7800×
        ui::dim("no labels")
781
    } else {
7820×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
783
    }
7840×
}
785
786
#[derive(Subcommand)]
787
enum CoverageCmd {
788
    /// Upload an LCOV or Cobertura report measured on this machine, as the
789
    /// coverage of a bookmark's current state (default: the default
790
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
791
    /// not measured by a runner, and sets no check from it
792
    Upload {
793
        file: std::path::PathBuf,
794
        #[arg(long)]
795
        bookmark: Option<String>,
796
        /// A change's full hash
797
        #[arg(long, conflicts_with = "bookmark")]
798
        change: Option<String>,
799
    },
800
}
801
802
#[derive(Subcommand)]
803
enum RunCmd {
804
    /// Recent runs, newest first
805
    List {
806
        #[arg(long, default_value_t = 20)]
807
        limit: i64,
808
    },
809
    /// A run and its jobs (default: the newest run)
810
    View {
811
        /// The run (default: the newest, or the newest of --bookmark)
812
        number: Option<i64>,
813
        /// With no number: the newest run of this bookmark
814
        #[arg(long, conflicts_with = "number")]
815
        bookmark: Option<String>,
816
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
817
        #[arg(long)]
818
        timings: bool,
819
    },
820
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
821
    Start {
822
        #[arg(long)]
823
        bookmark: Option<String>,
824
        /// A change's full hash
825
        #[arg(long, conflicts_with = "bookmark")]
826
        change: Option<String>,
827
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
828
        #[arg(long = "job", value_name = "NAME")]
829
        jobs: Vec<String>,
830
        /// Wait for the run and exit 1 unless it passes
831
        #[arg(long)]
832
        watch: bool,
833
    },
834
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
835
    Watch {
836
        /// The run (default: the newest, or the newest of --bookmark) (#367)
837
        number: Option<i64>,
838
        /// With no number: the newest run of this bookmark
839
        #[arg(long, conflicts_with = "number")]
840
        bookmark: Option<String>,
841
    },
842
    /// A job's log
843
    Log { number: i64, job: String },
844
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
845
    Report {
846
        number: i64,
847
        job: String,
848
        #[command(flatten)]
849
        pick: ReportPick,
850
    },
851
    /// Run a finished run's state again; with --job, only that job (and the
852
    /// jobs that depend on it) in the same run
853
    Rerun {
854
        number: i64,
855
        #[arg(long)]
856
        job: Option<String>,
857
    },
858
    /// Cancel a run still queued or running; its running jobs are stopped
859
    Cancel { number: i64 },
860
    /// Approve a job that waits for a person (oxygenflow#57)
861
    Approve {
862
        number: i64,
863
        #[arg(long)]
864
        job: String,
865
    },
866
    /// Reject a job that waits for a person: it ends cancelled
867
    Reject {
868
        number: i64,
869
        #[arg(long)]
870
        job: String,
871
    },
872
}
873
874
/// Which report of a job, and what of it to show.
875
#[derive(clap::Args)]
876
struct ReportPick {
877
    /// Which report, when the job published more than one
878
    #[arg(long)]
879
    name: Option<String>,
880
    /// What it holds: its metrics, context and files
881
    #[arg(long, conflicts_with = "file")]
882
    list: bool,
883
    /// One file of it (`data/frames.csv`), as published
884
    #[arg(long, value_name = "PATH")]
885
    file: Option<String>,
886
    /// Write the file here instead of to stdout
887
    #[arg(long, short, value_name = "FILE", requires = "file")]
888
    output: Option<std::path::PathBuf>,
889
}
890
891
#[derive(Subcommand)]
892
enum ReportCmd {
893
    /// The newest run of each report, newest first
894
    List {
895
        /// Only runs on this bookmark
896
        #[arg(long)]
897
        bookmark: Option<String>,
898
    },
899
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
900
    Show {
901
        report: String,
902
        #[arg(long, conflicts_with = "bookmark")]
903
        id: Option<i64>,
904
        #[arg(long)]
905
        bookmark: Option<String>,
906
        /// What it holds: its metrics, context and files
907
        #[arg(long, conflicts_with = "file")]
908
        list: bool,
909
        /// One file of it, as published
910
        #[arg(long, value_name = "PATH")]
911
        file: Option<String>,
912
        /// Write the file here instead of to stdout
913
        #[arg(long, short, value_name = "FILE", requires = "file")]
914
        output: Option<std::path::PathBuf>,
915
    },
916
}
917
918
#[derive(Subcommand)]
919
enum TagCmd {
920
    /// Tags, newest name first
921
    List,
922
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
923
    /// delegate (as `oxy tag create` and a push would be)
924
    Create {
925
        name: String,
926
        /// What to tag (default: the default bookmark)
927
        #[arg(long)]
928
        target: Option<String>,
929
        #[arg(long, short)]
930
        message: Option<String>,
931
    },
932
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
933
    /// their next fetch, and the name is never used again. Refused while a
934
    /// release uses the tag
935
    Delete {
936
        name: String,
937
        /// Why, recorded with the withdrawal
938
        #[arg(long, short)]
939
        reason: Option<String>,
940
    },
941
}
942
943
#[derive(Subcommand)]
944
enum ReleaseCmd {
945
    /// Releases, newest first
946
    List,
947
    /// Create a release on an existing tag
948
    Create {
949
        tag: String,
950
        #[arg(long, short)]
951
        title: Option<String>,
952
        /// Notes in Markdown (default: generated from the changes since the previous release)
953
        #[arg(long, short)]
954
        notes: Option<String>,
955
        #[arg(long)]
956
        prerelease: bool,
957
    },
958
    /// Change a release's title, notes or prerelease flag
959
    Edit {
960
        tag: String,
961
        #[arg(long, short)]
962
        title: Option<String>,
963
        /// New notes in Markdown ("-" reads them from stdin)
964
        #[arg(long, short)]
965
        notes: Option<String>,
966
        /// Mark it a prerelease (true) or not (false)
967
        #[arg(long)]
968
        prerelease: Option<bool>,
969
    },
970
    /// Attach files to a release
971
    Upload { tag: String, files: Vec<std::path::PathBuf> },
972
    /// The release's trust report: signatures, builds, receipts and audit
973
    Trust { tag: String },
974
}
975
97653×
fn main() {
977
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
978
    // other command-line tools do, instead of panicking on the failed
979
    // write (oxygenhub#92).
980
    #[cfg(unix)]
98153×
    unsafe {
98253×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
98353×
    }
98453×
    let cli = Cli::parse();
98553×
    ui::init(cli.plain);
98653×
    match run(cli) {
98745×
        Ok(code) => std::process::exit(code),
9888×
        Err(e) => {
9898×
            eprintln!("{} {e:#}", ui::bad("error:"));
9908×
            std::process::exit(2);
991
        }
992
    }
993
}
994
99522×
fn enc(s: &str) -> String {
99622×
    let mut out = String::new();
997109×
    for b in s.bytes() {
998109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
999108×
            out.push(b as char);
1000108×
        } else {
10011×
            out.push_str(&format!("%{b:02X}"));
10021×
        }
1003
    }
100422×
    out
100522×
}
1006
100753×
fn run(cli: Cli) -> Result<i32> {
100853×
    let cfg = Config::load()?;
10091×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
10101×
        return login(cfg, url, token.clone(), ca.clone());
101152×
    }
101252×
    let here = std::env::current_dir()?;
101352×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
101451×
    let c = Client::new(&t)?;
101551×
    let json = cli.json;
10160×
    match cli.cmd {
1017
        Cmd::Auth { cmd: AuthCmd::Status } => {
10180×
            let me: serde_json::Value = c.get("/user")?;
10190×
            if json {
10200×
                println!("{me}");
10210×
            } else {
10220×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
10230×
            }
10240×
            Ok(0)
1025
        }
10260×
        Cmd::Auth { .. } => unreachable!(),
10272×
        Cmd::Mcp { allow_write } => {
10282×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
10292×
            mcp::serve(c, t, allow_write)
1030
        }
10312×
        Cmd::Api { path, method, data } => {
10322×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
1033
            // The method applies with or without a body (#75): without one, a
1034
            // GET reads, anything else sends an empty object.
10352×
            let text = match data {
10360×
                Some(d) => c.send_text(
10370×
                    &method.to_uppercase(),
10380×
                    &path,
10390×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
10400×
                )?,
10412×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
10420×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
1043
            };
10442×
            println!("{text}");
10452×
            Ok(0)
1046
        }
10470×
        Cmd::Repo { cmd: RepoCmd::Create { slug, description, visibility, project, readme, licence, ignore, flow, wiki, bookmark } } => {
10480×
            let (owner, name) = slug.split_once('/').context("give the repository as OWNER/NAME")?;
10490×
            let project = match project.as_deref() {
10500×
                None => None,
10510×
                Some("new") => Some(serde_json::json!({ "new": "" })),
10520×
                Some(p) if p.starts_with("new:") => Some(serde_json::json!({ "new": &p[4..] })),
10530×
                Some(n) => {
10540×
                    Some(serde_json::json!({ "number": n.parse::<i64>().context("--project is new, new:TITLE or a board number")? }))
1055
                }
1056
            };
10570×
            let mut body = serde_json::json!({
10580×
                "owner": owner, "name": name, "description": description.unwrap_or_default(), "visibility": visibility, "readme": readme,
10590×
                "wiki": wiki,
1060
            });
10610×
            if let Some(f) = flow {
10620×
                body["flow"] = serde_json::json!(f);
10630×
            }
10640×
            if let Some(b) = bookmark {
10650×
                body["default_bookmark"] = serde_json::json!(b);
10660×
            }
10670×
            if let Some(p) = project {
10680×
                body["project"] = p;
10690×
            }
10700×
            if let Some(l) = licence {
10710×
                body["licence"] = serde_json::json!(l);
10720×
            }
10730×
            if let Some(i) = ignore {
10740×
                body["ignore"] = serde_json::json!(i);
10750×
            }
10760×
            let r: serde_json::Value = c.send("POST", "/repos", &body)?;
10770×
            if json {
10780×
                println!("{r}");
10790×
            } else {
10800×
                println!("{} created {owner}/{name} {}", ui::ok("✔"), ui::dim(r["url"].as_str().unwrap_or("")));
10810×
                println!("{}", ui::kv("clone", &format!("oxy clone {}/{owner}/{name}", t.hub)));
10820×
            }
10830×
            Ok(0)
1084
        }
1085
        Cmd::Repo { cmd: RepoCmd::View } => {
10861×
            let path = t.repo_path()?;
10871×
            if json {
10880×
                println!("{}", c.get_text(&path)?);
10890×
                return Ok(0);
10901×
            }
10911×
            let r: serde_json::Value = c.get(&path)?;
10921×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
10931×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
10941×
                println!("{d}");
10951×
            }
10961×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
10971×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
10981×
            Ok(0)
1099
        }
110018×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
11014×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
11023×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
11030×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
11040×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
11050×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
11060×
            let mut body = serde_json::json!({ "content": content });
11070×
            if let Some(b) = bookmark {
11080×
                body["bookmark"] = b.into();
11090×
            }
11100×
            if let Some(ch) = change {
11110×
                body["change"] = ch.into();
11120×
            }
11130×
            let base = t.repo_path()?;
11140×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
11150×
            if json {
11160×
                println!("{}", serde_json::to_string(&r)?);
1117
            } else {
11180×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
11190×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
11200×
                println!(
1121
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
11220×
                    ui::ok("✔"),
1123
                    r.lines_hit,
1124
                    r.lines_found,
1125
                    r.files,
11260×
                    ui::dim(&r.url)
1127
                );
11280×
                if r.dropped > 0 {
11290×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
11300×
                }
1131
            }
11320×
            Ok(0)
1133
        }
11344×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
11350×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
11360×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
11370×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
113810×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
11390×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
11400×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
11410×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
11427×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1143
    }
114453×
}
1145
1146
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
11472×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
11482×
    Ok(match v {
11490×
        None => None,
11502×
        Some("on") => Some(Some(true)),
11512×
        Some("off") => Some(Some(false)),
11522×
        Some("inherit") => Some(None),
11531×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1154
    })
11552×
}
1156
1157
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
11587×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
11597×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
11601×
    Ok(match kind {
11617×
        "site" if name.is_empty() => ("site".into(), String::new()),
11626×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
11635×
        "group" => {
11643×
            let g = all
11653×
                .groups
11663×
                .iter()
11673×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
11683×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
11693×
            ("group".into(), g.id.to_string())
1170
        }
11712×
        "runner" => {
11721×
            let r = all
11731×
                .runners
11741×
                .iter()
11751×
                .find(|r| r.id.to_string() == name || r.name == name)
11761×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
11770×
            ("runner".into(), r.id.to_string())
1178
        }
11791×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1180
    })
11817×
}
1182
11830×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
11840×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
11850×
    match cmd {
11860×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1187
        RunnerUpdatesCmd::Show => {
11880×
            println!(
1189
                "{} {}",
11900×
                ui::strong("Builds from"),
11910×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1192
            );
11930×
            for h in &all.holds {
11940×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
11950×
            }
11960×
            for s in &all.settings {
11970×
                let mut said = vec![];
11980×
                if let Some(u) = s.updates {
11990×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
12000×
                }
12010×
                if let Some(ch) = &s.channel {
12020×
                    said.push(format!("channel {ch}"));
12030×
                }
12040×
                if let Some(w) = &s.window {
12050×
                    said.push(format!("window {w} UTC"));
12060×
                }
12070×
                if let Some(d) = s.dry_run {
12080×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
12090×
                }
12100×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
12110×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1212
            }
12130×
            for g in &all.groups {
12140×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
12150×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
12160×
                if let Some(w) = g.wave {
12170×
                    what.push_str(&format!(", wave {w}"));
12180×
                }
12190×
                println!(
1220
                    "  group {} ({what}): {}",
12210×
                    ui::strong(&g.name),
12220×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1223
                );
1224
            }
12250×
            for r in &all.runners {
12260×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
12270×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1228
            }
1229
        }
12300×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
12310×
            let (scope, key) = update_scope(&scope, &all)?;
12320×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
12330×
                scope: scope.clone(),
12340×
                key: key.clone(),
12350×
                ..Default::default()
12360×
            });
12370×
            if let Some(u) = switch(updates.as_deref())? {
12380×
                s.updates = u;
12390×
            }
12400×
            if let Some(d) = switch(dry_run.as_deref())? {
12410×
                s.dry_run = d;
12420×
            }
12430×
            if let Some(ch) = channel {
12440×
                s.channel = Some(ch).filter(|c| c != "inherit");
12450×
            }
12460×
            if let Some(w) = window {
12470×
                s.window = Some(w).filter(|w| w != "inherit");
12480×
            }
12490×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
12500×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1251
        }
12520×
        RunnerUpdatesCmd::Lift { version } => {
12530×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
12540×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1255
        }
1256
    }
12570×
    Ok(0)
12580×
}
1259
1260
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
12617×
fn drop_id(s: &str) -> Result<String> {
12627×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1263144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
12641×
        bail!("{s:?} is not a drop's id or address");
12656×
    }
12666×
    Ok(id.to_ascii_lowercase())
12677×
}
1268
12692×
fn drop_line(d: &hub_api::Drop) -> String {
12702×
    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() };
12714×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
12722×
    format!(
1273
        "{} {} {}{}",
12742×
        ui::dim(&d.id),
12752×
        ui::strong(&title),
12762×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
12772×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1278
    )
12792×
}
1280
1281
/// `oh drop star|unstar` (oxygenhub#349).
12820×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
12830×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
12840×
    if json {
12850×
        println!("{}", serde_json::to_string(&s)?);
1286
    } else {
12870×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1288
    }
12890×
    Ok(())
12900×
}
1291
12927×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
12937×
    match cmd {
12941×
        DropCmd::Create { files, secret, description, title } => {
12951×
            let mut out = Vec::with_capacity(files.len());
12962×
            for f in &files {
12972×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
12982×
                let content =
12992×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
13002×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1301
            }
13021×
            let new =
13031×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
13041×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
13051×
            if json {
13061×
                println!("{}", serde_json::to_string(&d)?);
1307
            } else {
13080×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
13090×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1310
            }
1311
        }
13122×
        DropCmd::List { user } => {
13132×
            let path = match &user {
13141×
                Some(u) => format!("/users/{}/drops", enc(u)),
13151×
                None => "/drops".to_string(),
1316
            };
13172×
            if json {
13181×
                println!("{}", c.get_text(&path)?);
13191×
                return Ok(0);
13201×
            }
13211×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
13221×
            if list.is_empty() {
13230×
                println!("{}", ui::dim("No drops."));
13241×
            }
13251×
            for d in &list {
13261×
                println!("{}", drop_line(d));
13271×
            }
1328
        }
13293×
        DropCmd::View { id, file } => {
13303×
            let path = format!("/drops/{}", drop_id(&id)?);
13313×
            if json && file.is_none() {
13320×
                println!("{}", c.get_text(&path)?);
13330×
                return Ok(0);
13343×
            }
13353×
            let d: hub_api::Drop = c.get(&path)?;
13362×
            if let Some(name) = file {
13372×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
13381×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
13391×
                print!("{content}");
13401×
                return Ok(0);
13411×
            }
13421×
            println!("{}", drop_line(&d));
13431×
            if !d.description.is_empty() {
13441×
                println!("{}", d.description);
13451×
            }
13461×
            println!("{}", ui::kv("url", &d.url));
13471×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
13482×
            for f in &d.files {
13492×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
13502×
                match &f.content {
13512×
                    Some(text) => {
13522×
                        print!("{text}");
13532×
                        if !text.ends_with('\n') && !text.is_empty() {
13540×
                            println!();
13552×
                        }
1356
                    }
13570×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1358
                }
1359
            }
1360
        }
13611×
        DropCmd::Delete { id } => {
13621×
            let id = drop_id(&id)?;
13631×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
13641×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1365
        }
13660×
        DropCmd::Fork { id } => {
13670×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
13680×
            if json {
13690×
                println!("{}", serde_json::to_string(&d)?);
13700×
            } else {
13710×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
13720×
            }
1373
        }
13740×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
13750×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
13760×
        DropCmd::Comments { id } => {
13770×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
13780×
            if json {
13790×
                println!("{}", c.get_text(&path)?);
13800×
                return Ok(0);
13810×
            }
13820×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
13830×
            if list.is_empty() {
13840×
                println!("{}", ui::dim("No comments."));
13850×
            }
13860×
            for m in &list {
13870×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
13880×
                println!("{}\n", m.body);
13890×
            }
1390
        }
13910×
        DropCmd::Comment { id, message } => {
13920×
            let m: hub_api::DropComment =
13930×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
13940×
            if json {
13950×
                println!("{}", serde_json::to_string(&m)?);
13960×
            } else {
13970×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
13980×
            }
1399
        }
1400
    }
14014×
    Ok(0)
14027×
}
1403
1404
/// `30d`, `12h`, `90m` in milliseconds.
14050×
fn duration_ms(s: &str) -> Result<i64> {
14060×
    let s = s.trim();
14070×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
14080×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
14090×
    let per = match unit {
14100×
        "d" => 86_400_000,
14110×
        "h" => 3_600_000,
14120×
        "m" => 60_000,
14130×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1414
    };
14150×
    if n <= 0 {
14160×
        bail!("a grant must last some time");
14170×
    }
14180×
    Ok(n * per)
14190×
}
1420
14210×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1422
    use oxy_core::cert::{Grant, SignedGrant};
1423
    use oxy_core::identity::{Identity, Scope};
14240×
    match cmd {
14250×
        AgentCmd::Grant { name, scope, lasts } => {
14260×
            let home = oxy_core::repo::default_home();
14270×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
14280×
                format!(
1429
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
14300×
                    home.display()
1431
                )
14320×
            })?;
14330×
            let me: serde_json::Value = c.get("/user")?;
14340×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
14350×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
14360×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
14370×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14380×
            let grant = Grant {
14390×
                grantor: me_id.hash(),
14400×
                subject: format!("agent:{name}@{username}"),
14410×
                issuer: hub.hash(),
14420×
                scope,
14430×
                not_before: (now - 60_000) as u64,
14440×
                expires: (now + duration_ms(&lasts)?) as u64,
1445
            };
14460×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
14470×
            let r: serde_json::Value =
14480×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
14490×
            if json {
14500×
                println!("{r}");
14510×
                return Ok(0);
14520×
            }
14530×
            println!(
1454
                "{} {} to act for you as {} ({}), until {}",
14550×
                ui::ok("✔ granted"),
14560×
                ui::strong(&name),
14570×
                r["subject"].as_str().unwrap_or(""),
14580×
                r["scope"].as_str().unwrap_or(""),
14590×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1460
            );
14610×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
14620×
            println!(
1463
                "  {}",
14640×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1465
            );
14660×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
14670×
            Ok(0)
1468
        }
1469
        AgentCmd::List => {
14700×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
14710×
            if json {
14720×
                println!("{}", serde_json::to_string(&grants)?);
14730×
                return Ok(0);
14740×
            }
14750×
            if grants.is_empty() {
14760×
                println!("{}", ui::dim("no agent grants"));
14770×
            }
14780×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14790×
            for g in grants {
14800×
                let state = if g["revoked_ms"].is_i64() {
14810×
                    ui::bad("revoked")
14820×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
14830×
                    ui::dim("ended")
1484
                } else {
14850×
                    ui::ok("live")
1486
                };
14870×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
14880×
                println!(
1489
                    "#{:<4} {:<8} {} · {} · until {} · {}",
14900×
                    g["id"],
1491
                    state,
14920×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
14930×
                    g["scope"].as_str().unwrap_or(""),
14940×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
14950×
                    ui::dim(&used)
1496
                );
1497
            }
14980×
            Ok(0)
1499
        }
15000×
        AgentCmd::Revoke { id } => {
15010×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
15020×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
15030×
            Ok(0)
1504
        }
1505
    }
15060×
}
1507
15081×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
15091×
    let hub = url.trim_end_matches('/').to_string();
15101×
    let token = match token.as_deref() {
15111×
        Some("-") => {
15120×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
15130×
            let mut line = String::new();
15140×
            std::io::stdin().read_line(&mut line)?;
15150×
            line.trim().to_string()
1516
        }
15171×
        Some(t) => t.to_string(),
15180×
        None => device_sign_in(&hub, ca.clone())?,
1519
    };
15201×
    if token.is_empty() {
15210×
        bail!("no token given");
15221×
    }
15231×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
15241×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
15251×
    let account = me["username"].as_str().unwrap_or("?");
1526
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
15271×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
15281×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
15291×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
15301×
    cfg.default_hub = Some(hub.clone());
15311×
    cfg.save()?;
15321×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
15331×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
15341×
    Ok(0)
15351×
}
1536
1537
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1538
/// it on the web, and the token arrives here.
15390×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
15400×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
15410×
    let c = Client::new(&t)?;
15420×
    let host = std::fs::read_to_string("/etc/hostname")
15430×
        .ok()
15440×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
15450×
        .map(|h| h.trim().to_string())
15460×
        .filter(|h| !h.is_empty());
15470×
    let client = match host {
15480×
        Some(h) => format!("oh on {h}"),
15490×
        None => "oh".to_string(),
1550
    };
15510×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
15520×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
15530×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
15540×
    if code != 200 {
15550×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
15560×
    }
15570×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
15580×
    let user = v["user_code"].as_str().unwrap_or("?");
15590×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
15600×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
15610×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
15620×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
15630×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1564
    loop {
15650×
        std::thread::sleep(std::time::Duration::from_secs(interval));
15660×
        if std::time::Instant::now() > deadline {
15670×
            bail!("the code expired before it was approved; run oh auth login again");
15680×
        }
15690×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
15700×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
15710×
        if code == 200 {
15720×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
15730×
        }
15740×
        match v["error"].as_str() {
15750×
            Some("authorization_pending") => {}
15760×
            Some("slow_down") => interval += 5,
15770×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
15780×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
15790×
            _ => bail!("signing in: HTTP {code}: {body}"),
1580
        }
1581
    }
15820×
}
1583
158410×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
158510×
    match (body, file) {
15863×
        (Some(b), _) => Ok(b),
15871×
        (None, Some(f)) if f == "-" => {
15880×
            let mut s = String::new();
15890×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
15900×
            Ok(s)
1591
        }
15921×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
15936×
        (None, None) => Ok(String::new()),
1594
    }
159510×
}
1596
15973×
fn issue_line(i: &Issue) -> String {
15983×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
15993×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
16003×
    format!(
1601
        "{glyph} {} {}{}{}",
16023×
        ui::dim(&format!("#{}", i.number)),
1603
        i.title,
16043×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
16053×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1606
    )
16073×
}
1608
160918×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
161018×
    let base = t.repo_path()?;
161118×
    match cmd {
16123×
        IssueCmd::List { state } => {
16133×
            let path = format!("{base}/issues?state={}", enc(&state));
16143×
            if json {
16151×
                println!("{}", c.get_text(&path)?);
16161×
                return Ok(0);
16172×
            }
16182×
            let list: Vec<Issue> = c.get(&path)?;
16192×
            if list.is_empty() {
16201×
                println!("{}", ui::dim(&format!("No {state} issues.")));
16211×
            }
16222×
            for i in &list {
16232×
                println!("{}", issue_line(i));
16242×
            }
1625
        }
16262×
        IssueCmd::View { number } => {
16272×
            let path = format!("{base}/issues/{number}");
16282×
            if json {
16291×
                println!("{}", c.get_text(&path)?);
16301×
                return Ok(0);
16311×
            }
16321×
            let i: Issue = c.get(&path)?;
16331×
            println!("{}", issue_line(&i));
16341×
            if !i.body.trim().is_empty() {
16351×
                println!("\n{}\n", i.body.trim_end());
16361×
            }
16371×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
16382×
            for cm in comments {
16392×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
16402×
            }
16411×
            println!("{}", ui::dim(&i.url));
1642
        }
16434×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
16444×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16454×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
16464×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
16473×
            if json {
16481×
                println!("{}", serde_json::to_string(&i)?);
16492×
            } else {
16502×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16512×
            }
16523×
            if let Some(n) = project {
16531×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
16541×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
16551×
                if !json {
16561×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
16571×
                }
16582×
            }
1659
        }
16601×
        IssueCmd::Close { number, reason, comment } => {
16611×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
16621×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
16631×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1664
        }
16650×
        IssueCmd::Reopen { number, comment } => {
16660×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
16670×
            let i: Issue =
16680×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
16690×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1670
        }
16713×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
16723×
            let body = match (&body, &body_file) {
16733×
                (None, None) => None,
16740×
                _ => Some(body_of(body, body_file)?),
1675
            };
16763×
            let labels = if no_labels {
16771×
                Some(Vec::new())
16782×
            } else if label.is_empty() {
16791×
                None
1680
            } else {
16811×
                Some(label)
1682
            };
16833×
            let assignees = if no_assignees {
16841×
                Some(Vec::new())
16852×
            } else if assignee.is_empty() {
16861×
                None
1687
            } else {
16881×
                Some(assignee)
1689
            };
16903×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
16911×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
16922×
            }
16932×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
16942×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
16952×
            if json {
16961×
                println!("{}", serde_json::to_string(&i)?);
16971×
            } else {
16981×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16991×
            }
1700
        }
17010×
        IssueCmd::Label(change) => {
17020×
            let path = format!("{base}/issues/{}", change.number);
17030×
            let now: Issue = c.get(&path)?;
17040×
            let labels = change.apply(&now.labels)?;
17050×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
17060×
            let i: Issue = c.send("PATCH", &path, &edit)?;
17070×
            if json {
17080×
                println!("{}", serde_json::to_string(&i)?);
17090×
            } else {
17100×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
17110×
            }
1712
        }
17135×
        IssueCmd::Comment { number, body, body_file, attach } => {
17145×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
17154×
            if body.trim().is_empty() {
17161×
                bail!("give the comment with --body, --body-file or --attach");
17173×
            }
17183×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
17193×
            println!("{} commented on #{number}", ui::ok("✔"));
1720
        }
1721
    }
172212×
    Ok(0)
172318×
}
1724
1725
/// A comment to post with a close or reopen (#368): saying why, in the
1726
/// same command.
1727
#[derive(clap::Args)]
1728
struct StateComment {
1729
    /// Say why, as a comment posted first
1730
    #[arg(long, short)]
1731
    body: Option<String>,
1732
    /// Read the comment from a file ("-" for stdin)
1733
    #[arg(long, short = 'F', conflicts_with = "body")]
1734
    body_file: Option<String>,
1735
    /// Attach a file to the comment (repeatable)
1736
    #[arg(long, short = 'a', value_name = "FILE")]
1737
    attach: Vec<std::path::PathBuf>,
1738
}
1739
1740
impl StateComment {
17411×
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
17421×
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
17431×
            return Ok(());
17440×
        }
17450×
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
17460×
        if !body.trim().is_empty() {
17470×
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
17480×
        }
17490×
        Ok(())
17501×
    }
1751
}
1752
1753
/// `number`, or the newest run (of `bookmark`, when given): what a push
1754
/// just started is what one usually wants to follow (#367).
17551×
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
17561×
    if let Some(n) = number {
17571×
        return Ok(n);
17580×
    }
17590×
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
17600×
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
17610×
        Some(b) => format!("no runs of {b} among the latest 100"),
17620×
        None => "no runs yet".to_string(),
17630×
    })
17641×
}
1765
1766
/// `body` with each file attached to the repository and linked under it:
1767
/// an image shown in place, anything else a download (#350). Files are
1768
/// uploaded first, so a failed upload leaves nothing half made.
17699×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
17709×
    if files.is_empty() {
17716×
        return Ok(body);
17723×
    }
17733×
    let mut links = Vec::new();
17744×
    for f in files {
17754×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
17763×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
17773×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
17783×
        let a: hub_api::Attachment =
17793×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
17803×
        links.push(a.markdown);
1781
    }
17822×
    let links = links.join("\n\n");
17832×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
17849×
}
1785
17861×
fn source_name(s: &hub_api::ProposalSource) -> String {
17871×
    match s {
17881×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
17890×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
17900×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1791
    }
17921×
}
1793
17941×
fn proposal_line(p: &Proposal) -> String {
17951×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
17961×
    let glyph = match state.as_str() {
17971×
        "open" => ui::ok("●"),
17980×
        "draft" => ui::dim("◌"),
17990×
        "landed" => ui::strong("✔"),
18000×
        _ => ui::dim("○"),
1801
    };
18021×
    format!(
1803
        "{glyph} {} {} {}{}",
18041×
        ui::dim(&format!("#{}", p.number)),
1805
        p.title,
18061×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
18071×
        ui::dim(&format!(" · {} · {state}", p.author))
1808
    )
18091×
}
1810
18114×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
18124×
    let base = t.repo_path()?;
18134×
    match cmd {
18140×
        ProposalCmd::List { state, limit } => {
18150×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
18160×
            if json {
18170×
                println!("{}", c.get_text(&path)?);
18180×
                return Ok(0);
18190×
            }
18200×
            let list: Vec<Proposal> = c.get(&path)?;
18210×
            if list.is_empty() {
18220×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
18230×
            }
18240×
            for p in &list {
18250×
                println!("{}", proposal_line(p));
18260×
            }
1827
        }
18281×
        ProposalCmd::View { number } => {
18291×
            let path = format!("{base}/proposals/{number}");
18301×
            if json {
18310×
                println!("{}", c.get_text(&path)?);
18320×
                return Ok(0);
18331×
            }
18341×
            let p: Proposal = c.get(&path)?;
18351×
            println!("{}", proposal_line(&p));
18361×
            if !p.body.trim().is_empty() {
18370×
                println!("\n{}\n", p.body.trim_end());
18381×
            }
18391×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
18401×
            for ch in &p.changes {
18411×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
18421×
            }
18431×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
18441×
            if p.landable {
18451×
                println!("{} can land", ui::ok("✔"));
18461×
            } else {
18470×
                for b in &p.blockers {
18480×
                    println!("{} {b}", ui::bad("✘"));
18490×
                }
1850
            }
18511×
            if p.conflicted {
18520×
                println!("{} landing it would leave conflicts", ui::bad("!"));
18531×
            }
18541×
            println!("{}", ui::dim(&p.url));
1855
        }
18561×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
18571×
            let target = match into {
18580×
                Some(i) => i,
18591×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1860
            };
18611×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
18621×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
18631×
            if json {
18640×
                println!("{}", serde_json::to_string(&p)?);
18651×
            } else {
18661×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18671×
            }
1868
        }
18690×
        ProposalCmd::Edit { number, title, body, body_file } => {
18700×
            let body = match (&body, &body_file) {
18710×
                (None, None) => None,
18720×
                _ => Some(body_of(body, body_file)?),
1873
            };
18740×
            if title.is_none() && body.is_none() {
18750×
                bail!("say what to change: --title, --body or --body-file");
18760×
            }
18770×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
18780×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18790×
            if json {
18800×
                println!("{}", serde_json::to_string(&p)?);
18810×
            } else {
18820×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18830×
            }
1884
        }
18850×
        ProposalCmd::Label(change) => {
18860×
            let path = format!("{base}/proposals/{}", change.number);
18870×
            let now: Proposal = c.get(&path)?;
18880×
            let labels = change.apply(&now.labels)?;
18890×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
18900×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
18910×
            if json {
18920×
                println!("{}", serde_json::to_string(&p)?);
18930×
            } else {
18940×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
18950×
            }
1896
        }
18970×
        ProposalCmd::Comment { number, body, body_file } => {
18980×
            let body = body_of(body, body_file)?;
18990×
            if body.trim().is_empty() {
19000×
                bail!("give the comment with --body or --body-file");
19010×
            }
19020×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
19030×
            println!("{} commented on #{number}", ui::ok("✔"));
1904
        }
19050×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
19060×
            let path = format!("{base}/proposals/{number}/auto-land");
19070×
            let p: Proposal =
19080×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
19090×
            if json {
19100×
                println!("{}", serde_json::to_string(&p)?);
19110×
            } else if p.landed.is_some() {
19120×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
19130×
            } else if p.auto_land.is_some() {
19140×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
19150×
            } else {
19160×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
19170×
            }
1918
        }
19192×
        ProposalCmd::Land { number, over_checks, .. } => {
19202×
            let body = match &over_checks {
19210×
                Some(r) => serde_json::json!({ "over_checks": r }),
19222×
                None => serde_json::json!({}),
1923
            };
19242×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
19251×
            if json {
19260×
                println!("{}", serde_json::to_string(&p)?);
19271×
            } else {
19281×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
19291×
            }
1930
        }
19310×
        ProposalCmd::Close { number, message } => {
19320×
            if let Some(body) = message {
19330×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
19340×
            }
19350×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
19360×
            if json {
19370×
                println!("{}", serde_json::to_string(&p)?);
19380×
            } else {
19390×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
19400×
            }
1941
        }
19420×
        ProposalCmd::Reopen { number } => {
19430×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
19440×
            if json {
19450×
                println!("{}", serde_json::to_string(&p)?);
19460×
            } else {
19470×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
19480×
            }
1949
        }
19500×
        ProposalCmd::Ready { number, undo } => {
19510×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
19520×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
19530×
            if json {
19540×
                println!("{}", serde_json::to_string(&p)?);
19550×
            } else if undo {
19560×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
19570×
            } else {
19580×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
19590×
            }
1960
        }
19610×
        ProposalCmd::Checks { number } => {
19620×
            let path = format!("{base}/proposals/{number}/checks");
19630×
            if json {
19640×
                println!("{}", c.get_text(&path)?);
19650×
                return Ok(0);
19660×
            }
19670×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
19680×
            if checks.is_empty() {
19690×
                println!("{}", ui::dim("No checks yet."));
19700×
            }
19710×
            for ch in checks {
19720×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
19730×
            }
1974
        }
1975
    }
19763×
    Ok(0)
19774×
}
1978
19791×
fn run_line(r: &FlowRun) -> String {
19801×
    let what =
19811×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
19821×
    format!(
1983
        "{} {} {} {}",
19841×
        ui::status(&r.status),
19851×
        ui::dim(&format!("#{}", r.number)),
1986
        what,
19871×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1988
    )
19891×
}
1990
19911×
fn print_run(r: &FlowRun, timings: bool) {
19921×
    println!("{}", run_line(r));
19931×
    for j in &r.jobs {
19941×
        let dur = match (j.started_ms, j.finished_ms) {
19950×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
19961×
            _ => String::new(),
1997
        };
19981×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
19991×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
2000
        // Why a queued job no runner can take waits (oxygenhub#28), and
2001
        // why a job ran where it did (oxygenflow#42).
20021×
        if j.status == "queued" && !j.waiting.is_empty() {
20030×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
20041×
        } else if !j.placed.is_empty() {
20050×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
20061×
        }
20071×
        if timings {
20080×
            let t = timing_line(j);
20090×
            if !t.is_empty() {
20100×
                println!("    {}", ui::dim(&t));
20110×
            }
20121×
        }
2013
    }
20141×
    if !r.error.is_empty() {
20150×
        println!("{}", ui::bad(&r.error));
20161×
    }
20171×
    println!("{}", ui::dim(&r.url));
20181×
}
2019
2020
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
20213×
fn took(ms: i64) -> String {
20223×
    match ms {
20233×
        ..=999 => format!("{ms} ms"),
20242×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
20251×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
2026
    }
20273×
}
2028
2029
/// MiB as a person reads them.
20302×
fn mib(m: i64) -> String {
20312×
    if m >= 1024 {
20321×
        format!("{:.1} GiB", m as f64 / 1024.0)
2033
    } else {
20341×
        format!("{m} MiB")
2035
    }
20362×
}
2037
2038
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
2039
/// phase its runner reported, and the most disk and memory it took.
20402×
fn timing_line(j: &FlowJob) -> String {
20412×
    let mut parts = vec![];
20422×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
20431×
        parts.push(format!("waited {}", took((s - q).max(0))));
20441×
    }
20452×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
20462×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
20472×
        .into_iter()
20484×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
20492×
        .collect();
20502×
    if !peaks.is_empty() {
20511×
        parts.push(format!("peak {}", peaks.join(", ")));
20521×
    }
20532×
    parts.join(" · ")
20542×
}
2055
2056
/// A report's path, its segments encoded and its slashes kept.
20571×
fn enc_path(path: &str) -> String {
20581×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
20591×
}
2060
2061
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
2062
/// files are at `files(path)`. By default its report.toml; with `list`
2063
/// what it holds; with `file` one file, to stdout or `output`.
20640×
fn show_report(
20650×
    c: &Client,
20660×
    at: &str,
20670×
    files: impl Fn(&str) -> String,
20680×
    list: bool,
20690×
    file: Option<String>,
20700×
    output: Option<std::path::PathBuf>,
20710×
    json: bool,
20720×
) -> Result<()> {
2073
    use std::io::Write;
20740×
    if let Some(path) = file {
20750×
        let bytes = c.get_bytes(&files(&path))?;
20760×
        match output {
20770×
            Some(out) => {
20780×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
20790×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
2080
            }
20810×
            None => std::io::stdout().write_all(&bytes)?,
2082
        }
20830×
        return Ok(());
20840×
    }
20850×
    if json {
20860×
        println!("{}", c.get_text(at)?);
20870×
        return Ok(());
20880×
    }
20890×
    if !list {
20900×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
20910×
        return Ok(());
20920×
    }
20930×
    let r: Report = c.get(at)?;
20940×
    print_report(&r);
20950×
    if r.files_expired_ms.is_some() {
20960×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
20970×
    }
20980×
    for f in &r.manifest {
20990×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
21000×
    }
21010×
    println!("{}", ui::dim(&r.url));
21020×
    Ok(())
21030×
}
2104
2105
/// A report's heading, metrics and context.
21060×
fn print_report(r: &Report) {
21070×
    let from = match r.run {
21080×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
21090×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2110
    };
21110×
    println!(
2112
        "{} {} {}",
21130×
        ui::strong(&r.name),
21140×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
21150×
        ui::dim(&format!("· {from} · {} files", r.files))
2116
    );
21170×
    if !r.summary.is_empty() {
21180×
        println!("  {}", r.summary);
21190×
    }
21200×
    for m in &r.metrics {
21210×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
21220×
        let mut notes = vec![];
21230×
        if !m.better.is_empty() {
21240×
            notes.push(format!("{} is better", m.better));
21250×
        }
21260×
        if let Some(a) = m.fail_above {
21270×
            notes.push(format!("fails above {a}"));
21280×
        }
21290×
        if let Some(b) = m.fail_below {
21300×
            notes.push(format!("fails below {b}"));
21310×
        }
21320×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
21330×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2134
    }
21350×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
21360×
        let line: Vec<String> =
21370×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
21380×
        println!("  {}", ui::dim(&line.join(" ")));
21390×
    }
21400×
}
2141
2142
/// `oh report …` (oxygenhub#348).
21430×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
21440×
    let base = t.repo_path()?;
21450×
    match cmd {
21460×
        ReportCmd::List { bookmark } => {
21470×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
21480×
            if json {
21490×
                println!("{}", c.get_text(&path)?);
21500×
                return Ok(0);
21510×
            }
21520×
            let list: Vec<Report> = c.get(&path)?;
21530×
            if list.is_empty() {
21540×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
21550×
            }
21560×
            for r in &list {
21570×
                print_report(r);
21580×
            }
2159
        }
21600×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
21610×
            let at = format!("{base}/reports/{}", enc(&report));
21620×
            let query = match (id, bookmark) {
21630×
                (Some(id), _) => format!("?id={id}"),
21640×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
21650×
                (None, None) => String::new(),
2166
            };
21670×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
21680×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2169
        }
2170
    }
21710×
    Ok(0)
21720×
}
2173
21740×
fn live(status: &str) -> bool {
21750×
    matches!(status, "queued" | "running")
21760×
}
2177
2178
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
21790×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
21800×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
21810×
    if json {
21820×
        println!("{done}");
21830×
    } else {
21840×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
21850×
    }
21860×
    Ok(())
21870×
}
2188
21890×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
21900×
    let path = format!("{base}/flow/runs/{number}");
21910×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2192
    loop {
21930×
        let r: FlowRun = c.get(&path)?;
21940×
        if !json {
21950×
            for j in &r.jobs {
21960×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
21970×
                if seen.get(&j.name) != Some(&shown) {
21980×
                    println!("{} {}", ui::status(&j.status), j.name);
21990×
                    if j.status == "queued" && !j.waiting.is_empty() {
22000×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
22010×
                    }
22020×
                    seen.insert(j.name.clone(), shown);
22030×
                }
2204
            }
22050×
        }
22060×
        if !live(&r.status) {
22070×
            if json {
22080×
                println!("{}", serde_json::to_string(&r)?);
22090×
            } else {
22100×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
22110×
            }
22120×
            return Ok(if r.status == "passed" { 0 } else { 1 });
22130×
        }
22140×
        std::thread::sleep(Duration::from_secs(3));
2215
    }
22160×
}
2217
22183×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
22193×
    let base = t.repo_path()?;
22200×
    match cmd {
22211×
        RunCmd::List { limit } => {
22221×
            let path = format!("{base}/flow/runs?limit={limit}");
22231×
            if json {
22241×
                println!("{}", c.get_text(&path)?);
22251×
                return Ok(0);
22260×
            }
22270×
            let runs: Vec<FlowRun> = c.get(&path)?;
22280×
            if runs.is_empty() {
22290×
                println!("{}", ui::dim("No runs yet."));
22300×
            }
22310×
            for r in &runs {
22320×
                println!("{}", run_line(r));
22330×
            }
2234
        }
22351×
        RunCmd::View { number, bookmark, timings } => {
22361×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
22371×
            let path = format!("{base}/flow/runs/{number}");
22381×
            if json {
22390×
                println!("{}", c.get_text(&path)?);
22400×
                return Ok(0);
22411×
            }
22421×
            print_run(&c.get(&path)?, timings);
2243
        }
22441×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
22451×
            let mut body = match (bookmark, change) {
22460×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
22470×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
22481×
                (None, None) => serde_json::json!({}),
2249
            };
22501×
            if !jobs.is_empty() {
22510×
                body["jobs"] = serde_json::json!(jobs);
22521×
            }
22531×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
22541×
            let n = started["number"].as_i64().context("the hub named no run")?;
22551×
            if !json || !follow {
22561×
                if json {
22570×
                    println!("{started}");
22581×
                } else {
22591×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
22601×
                }
22610×
            }
22621×
            if follow {
22630×
                return watch(c, &base, n, json);
22641×
            }
2265
        }
22660×
        RunCmd::Watch { number, bookmark } => {
22670×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
22680×
            return watch(c, &base, number, json);
2269
        }
22700×
        RunCmd::Log { number, job } => {
22710×
            let mut after = 0;
2272
            loop {
22730×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
22740×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
22750×
                if lines.is_empty() {
22760×
                    break;
22770×
                }
22780×
                for l in &lines {
22790×
                    if json {
22800×
                        println!("{}", serde_json::to_string(l)?);
22810×
                    } else if l.stream == "flow" {
22820×
                        println!("{}", ui::dim(&l.text));
22830×
                    } else {
22840×
                        println!("{}", l.text);
22850×
                    }
2286
                }
22870×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2288
            }
2289
        }
22900×
        RunCmd::Report { number, job, pick } => {
22910×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
22920×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
22930×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
22940×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2295
        }
22960×
        RunCmd::Rerun { number, job: Some(job) } => {
22970×
            let queued: serde_json::Value =
22980×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
22990×
            if json {
23000×
                println!("{queued}");
23010×
            } else {
23020×
                let n = queued["queued"].as_i64().unwrap_or(1);
23030×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
23040×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2305
            }
2306
        }
23070×
        RunCmd::Rerun { number, job: None } => {
23080×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
23090×
            if json {
23100×
                println!("{started}");
23110×
            } else {
23120×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
23130×
            }
2314
        }
23150×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
23160×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
23170×
        RunCmd::Cancel { number } => {
23180×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
23190×
            if json {
23200×
                println!("{done}");
23210×
            } else {
23220×
                println!("{} cancelled run #{number}", ui::ok("✔"));
23230×
            }
2324
        }
2325
    }
23262×
    Ok(0)
23273×
}
2328
23290×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
23300×
    let base = t.repo_path()?;
23310×
    match cmd {
2332
        LabelCmd::List => {
23330×
            let path = format!("{base}/labels");
23340×
            if json {
23350×
                println!("{}", c.get_text(&path)?);
23360×
                return Ok(0);
23370×
            }
23380×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
23390×
            if labels.is_empty() {
23400×
                println!("{}", ui::dim("No labels."));
23410×
            }
23420×
            for l in labels {
23430×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
23440×
            }
2345
        }
23460×
        LabelCmd::Create { name, colour, description } => {
23470×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
23480×
            if json {
23490×
                println!("{}", serde_json::to_string(&l)?);
23500×
            } else {
23510×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
23520×
            }
2353
        }
23540×
        LabelCmd::Delete { name } => {
23550×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
23560×
            println!("{} deleted label {name}", ui::ok("✔"));
2357
        }
2358
    }
23590×
    Ok(0)
23600×
}
2361
23620×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
23630×
    let base = match (&org, site) {
23640×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
23650×
        (None, true) => "/admin/assistants".to_string(),
23660×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2367
    };
23680×
    match cmd {
2369
        AssistantCmd::List => {
23700×
            if json {
23710×
                println!("{}", c.get_text(&base)?);
23720×
                return Ok(0);
23730×
            }
23740×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
23750×
            if list.is_empty() {
23760×
                println!("{}", ui::dim("No assistants."));
23770×
            }
23780×
            for a in list {
23790×
                let state = if a.enabled && !a.off_above {
23800×
                    ui::ok("on")
23810×
                } else if a.off_above {
23820×
                    ui::dim("off above")
2383
                } else {
23840×
                    ui::dim("off")
2385
                };
23860×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
23870×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2388
            }
2389
        }
23900×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
23910×
            let token = match token_env {
23920×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
23930×
                None => String::new(),
2394
            };
23950×
            let body =
23960×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
23970×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
23980×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2399
        }
24000×
        AssistantCmd::Remove { name } => {
24010×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
24020×
            println!("{} removed {name}", ui::ok("✔"));
2403
        }
24040×
        AssistantCmd::Prompt { set } => {
24050×
            let p: hub_api::AssistantPrompt = match set {
24060×
                Some(path) => {
24070×
                    let text = if path.as_os_str() == "-" {
24080×
                        let mut s = String::new();
24090×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
24100×
                        s
2411
                    } else {
24120×
                        std::fs::read_to_string(&path)?
2413
                    };
24140×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2415
                }
24160×
                None => c.get(&format!("{base}/prompt"))?,
2417
            };
24180×
            if json {
24190×
                println!("{}", serde_json::to_string(&p)?);
24200×
                return Ok(0);
24210×
            }
24220×
            for (from, text) in &p.inherited {
24230×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
24240×
            }
24250×
            if p.prompt.is_empty() {
24260×
                println!("{}", ui::dim("No prompt of its own."));
24270×
            } else {
24280×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
24290×
            }
2430
        }
2431
    }
24320×
    Ok(0)
24330×
}
2434
24352×
fn project_line(p: &hub_api::Project) -> String {
24362×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
24372×
    let private = if p.public { "" } else { " · private" };
24382×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
24392×
}
2440
244110×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
244210×
    let owner = match owner {
24430×
        Some(o) => o,
244410×
        None => t.repo()?.0.to_string(),
2445
    };
244610×
    let base = format!("/projects/{}", enc(&owner));
244710×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
24481×
        let p: hub_api::Project =
24491×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
24501×
        if json {
24510×
            println!("{}", serde_json::to_string(&p)?);
24521×
        } else {
24531×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
24541×
        }
24551×
        Ok(())
24561×
    };
24574×
    match cmd {
2458
        ProjectCmd::List => {
24591×
            if json {
24600×
                println!("{}", c.get_text(&base)?);
24610×
                return Ok(0);
24621×
            }
24631×
            let list: Vec<hub_api::Project> = c.get(&base)?;
24641×
            if list.is_empty() {
24650×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
24661×
            }
24671×
            for p in &list {
24681×
                println!("{}", project_line(p));
24691×
            }
2470
        }
24713×
        ProjectCmd::View { number, archived, filter, view } => {
24723×
            let cards = format!("{base}/{number}/cards?archived=true");
24733×
            let path = match (&filter, &view) {
24740×
                (Some(q), _) => format!("{base}/{number}?q={}", enc(q)),
24750×
                (None, Some(v)) => format!("{base}/{number}?view={}", enc(v)),
24763×
                (None, None) => format!("{base}/{number}"),
2477
            };
24783×
            if json {
24792×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
24802×
                return Ok(0);
24811×
            }
24821×
            let mut b: hub_api::Board = c.get(&path)?;
24831×
            if archived {
24840×
                b.columns = c.get(&cards)?;
24851×
            }
24861×
            println!("{}", project_line(&b.project));
24871×
            if !b.project.description.is_empty() {
24881×
                println!("{}", b.project.description);
24891×
            }
24901×
            if !b.filter.is_empty() {
24910×
                println!("{}", ui::dim(&format!("filter: {}", b.filter)));
24921×
            }
24931×
            if !b.views.is_empty() && filter.is_none() && view.is_none() {
24940×
                let names: Vec<&str> = b.views.iter().map(|v| v.name.as_str()).collect();
24950×
                println!("{}", ui::dim(&format!("views: {} (oh project view {number} --view NAME)", names.join(", "))));
24961×
            }
24973×
            for col in &b.columns {
24983×
                println!();
24993×
                let wip = match col.wip_limit {
25000×
                    Some(w) if col.cards.len() as i64 > w => format!(" · over its limit of {w}"),
25010×
                    Some(w) => format!(" · limit {w}"),
25023×
                    None => String::new(),
2503
                };
25043×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}{wip}", col.cards.len(), col.id)));
25053×
                if col.cards.is_empty() {
25061×
                    println!("  {}", ui::dim("(empty)"));
25072×
                }
25083×
                for card in &col.cards {
25092×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
25102×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
25112×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
25122×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
25132×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
25142×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2515
                }
2516
            }
25171×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2518
        }
25191×
        ProjectCmd::Create { title, description, private } => {
25201×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
25211×
            if json {
25220×
                println!("{}", serde_json::to_string(&p)?);
25231×
            } else {
25241×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
25251×
            }
2526
        }
25270×
        ProjectCmd::Charts { number, filter } => {
25280×
            let path = match &filter {
25290×
                Some(q) => format!("{base}/{number}/charts?q={}", enc(q)),
25300×
                None => format!("{base}/{number}/charts"),
2531
            };
25320×
            if json {
25330×
                println!("{}", c.get_text(&path)?);
25340×
                return Ok(0);
25350×
            }
25360×
            let ch: hub_api::BoardCharts = c.get(&path)?;
25370×
            println!("{}", ui::strong("Forecasts"));
25380×
            for f in &ch.forecasts {
25390×
                let when = match (&f.p50, &f.p85) {
25400×
                    (Some(a), Some(b)) => format!("50% by {a}, 85% by {b}"),
25410×
                    (Some(a), None) => format!("50% by {a}, 85% beyond ten years"),
25420×
                    _ => "no forecast: nothing has reached Done in the weeks it draws from".to_string(),
2543
                };
25440×
                println!("  {}  {} left · {when}", f.scope, f.remaining);
2545
            }
25460×
            if let Some(f) = ch.forecasts.first() {
25470×
                println!("  {}", ui::dim(&format!("from {} week(s) of throughput", f.weeks_of_history)));
25480×
            }
25490×
            println!();
25500×
            match (ch.cycle_time_median_days, ch.cycle_time_p85_days) {
25510×
                (Some(m), Some(p)) => {
25520×
                    println!("{} median {m} d, 85th percentile {p} d over {} finished", ui::strong("Cycle time"), ch.finished)
2553
                }
25540×
                _ => println!("{} {}", ui::strong("Cycle time"), ui::dim("no card has gone from started to Done yet")),
2555
            }
25560×
            let weeks: Vec<String> = ch.throughput.iter().map(|w| w.done.to_string()).collect();
25570×
            println!("{} {} {}", ui::strong("Throughput"), weeks.join(" "), ui::dim("(cards done each week, oldest first)"));
25580×
            if let Some(b) = &ch.burn_down {
25590×
                println!(
25600×
                    "{} {}: {} left of {}",
25610×
                    ui::strong("Burn-down"),
25620×
                    b.iteration,
25630×
                    b.left.last().unwrap_or(&0),
25640×
                    b.scope.last().unwrap_or(&0)
25650×
                );
25660×
            }
2567
        }
25680×
        ProjectCmd::Column { cmd } => {
25690×
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
25700×
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
25710×
                ColumnCmd::Add { number, name } => {
25720×
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
25730×
                    (number, b, format!("added column {name}"))
2574
                }
25750×
                ColumnCmd::Rename { number, column, to } => {
25760×
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
25770×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2578
                }
25790×
                ColumnCmd::Move { number, column, to, left, right } => {
25800×
                    let position = match to {
25810×
                        Some(n) => n - 1,
2582
                        None => {
25830×
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
25840×
                            let at = now
25850×
                                .columns
25860×
                                .iter()
25870×
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
25880×
                                .with_context(|| format!("no column {column} on board {number}"))?
2589
                                as i64;
25900×
                            if left {
25910×
                                (at - 1).max(0)
2592
                            } else {
25930×
                                debug_assert!(right);
25940×
                                at + 1
2595
                            }
2596
                        }
2597
                    };
25980×
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
25990×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2600
                }
26010×
                ColumnCmd::Remove { number, column } => {
26020×
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2603
                }
2604
            };
26050×
            if json {
26060×
                println!("{}", serde_json::to_string(&b)?);
2607
            } else {
26080×
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
26090×
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2610
            }
2611
        }
26121×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
26130×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
26140×
        ProjectCmd::Transfer { number, to } => {
26150×
            let p: hub_api::Project =
26160×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
26170×
            if json {
26180×
                println!("{}", serde_json::to_string(&p)?);
26190×
            } else {
26200×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
26210×
            }
2622
        }
26232×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2624
            // The hub names a card's issue as `repo#N` among the owner's
2625
            // repositories.
26262×
            let reference = match reference {
26271×
                None => String::new(),
26281×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
26290×
                    Some((o, rest)) if o == owner => rest.to_string(),
26300×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
26310×
                    None => r,
2632
                },
26331×
                Some(r) => {
26341×
                    let n = r.trim_start_matches('#');
26351×
                    if n.parse::<i64>().is_err() {
26360×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
26371×
                    }
26381×
                    format!("{}#{n}", t.repo()?.1)
2639
                }
2640
            };
26412×
            let note = note.unwrap_or_default();
26422×
            if reference.is_empty() && note.is_empty() {
26430×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
26442×
            }
26451×
            let card: hub_api::ProjectCard =
26462×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
26471×
            if json {
26480×
                println!("{}", serde_json::to_string(&card)?);
2649
            } else {
26501×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2651
            }
2652
        }
26531×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
26541×
            (Some(card), None) => {
26551×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
26561×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2657
            }
26580×
            (None, Some(from)) => {
26590×
                let r: hub_api::CardsMoved = c.send(
26600×
                    "POST",
26610×
                    &format!("{base}/{number}/cards/move"),
26620×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
26630×
                )?;
26640×
                if json {
26650×
                    println!("{}", serde_json::to_string(&r)?);
26660×
                    return Ok(0);
26670×
                }
26680×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
26690×
                for m in &r.moved {
26700×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2671
                }
26720×
                let verb = if dry_run { "would move" } else { "moved" };
26730×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2674
            }
26750×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2676
        },
26770×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
26780×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
26790×
                None => None,
26800×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2681
            };
26820×
            let r: hub_api::CardsArchived = c.send(
26830×
                "POST",
26840×
                &format!("{base}/{number}/cards/archive"),
26850×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
26860×
            )?;
26870×
            if json {
26880×
                println!("{}", serde_json::to_string(&r)?);
26890×
                return Ok(0);
26900×
            }
26910×
            let verb = if dry_run { "would archive" } else { "archived" };
26920×
            for a in &r.archived {
26930×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
26940×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2695
            }
26960×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2697
        }
26980×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
26990×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
27000×
            println!("{} card {card} restored", ui::ok("✔"));
2701
        }
27021×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
27031×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
27041×
            println!("{} card {card} removed", ui::ok("✔"));
2705
        }
2706
    }
27077×
    Ok(0)
270810×
}
2709
27100×
fn milestone_line(m: &hub_api::Milestone) -> String {
27110×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
27120×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
27130×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
27140×
}
2715
27160×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
27170×
    let base = t.repo_path()?;
27180×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
27190×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
27200×
        if json {
27210×
            println!("{}", serde_json::to_string(&m)?);
27220×
        } else {
27230×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
27240×
        }
27250×
        Ok(())
27260×
    };
27270×
    match cmd {
2728
        MilestoneCmd::List => {
27290×
            let path = format!("{base}/milestones");
27300×
            if json {
27310×
                println!("{}", c.get_text(&path)?);
27320×
                return Ok(0);
27330×
            }
27340×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
27350×
            if list.is_empty() {
27360×
                println!("{}", ui::dim("No milestones."));
27370×
            }
27380×
            for m in &list {
27390×
                println!("{}", milestone_line(m));
27400×
            }
2741
        }
27420×
        MilestoneCmd::Create { title, description, due } => {
27430×
            let m: hub_api::Milestone =
27440×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
27450×
            if json {
27460×
                println!("{}", serde_json::to_string(&m)?);
27470×
            } else {
27480×
                println!("{} milestone {}", ui::ok("✔"), m.title);
27490×
            }
2750
        }
27510×
        MilestoneCmd::Edit { title, rename, description, due } => {
27520×
            if rename.is_none() && description.is_none() && due.is_none() {
27530×
                bail!("say what to change: --rename, --description or --due");
27540×
            }
27550×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2756
        }
27570×
        MilestoneCmd::Close { title } => {
27580×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2759
        }
27600×
        MilestoneCmd::Reopen { title } => {
27610×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2762
        }
2763
    }
27640×
    Ok(0)
27650×
}
2766
27670×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
27680×
    let base = t.repo_path()?;
27690×
    match cmd {
2770
        TagCmd::List => {
27710×
            let path = format!("{base}/tags");
27720×
            if json {
27730×
                println!("{}", c.get_text(&path)?);
27740×
                return Ok(0);
27750×
            }
27760×
            let tags: Vec<Tag> = c.get(&path)?;
27770×
            if tags.is_empty() {
27780×
                println!("{}", ui::dim("no tags"));
27790×
            }
27800×
            for t in tags {
27810×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
27820×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
27830×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2784
            }
2785
        }
27860×
        TagCmd::Create { name, target, message } => {
27870×
            let new = hub_api::NewTag { name, target, message };
27880×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
27890×
            if json {
27900×
                println!("{}", serde_json::to_string(&made)?);
27910×
            } else {
27920×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
27930×
            }
2794
        }
27950×
        TagCmd::Delete { name, reason } => {
27960×
            let reason = reason.unwrap_or_default();
27970×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
27980×
            if json {
27990×
                println!("{}", serde_json::json!({ "withdrawn": name }));
28000×
            } else {
28010×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
28020×
            }
2803
        }
2804
    }
28050×
    Ok(0)
28060×
}
2807
28084×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
28094×
    let base = t.repo_path()?;
28104×
    match cmd {
2811
        ReleaseCmd::List => {
28121×
            let path = format!("{base}/releases");
28131×
            if json {
28141×
                println!("{}", c.get_text(&path)?);
28151×
                return Ok(0);
28160×
            }
28170×
            let list: Vec<Release> = c.get(&path)?;
28180×
            if list.is_empty() {
28190×
                println!("{}", ui::dim("No releases."));
28200×
            }
28210×
            for r in &list {
28220×
                println!(
2823
                    "{} {} {}{}",
28240×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
28250×
                    ui::strong(&r.tag),
2826
                    r.title,
28270×
                    ui::dim(&format!(
2828
                        " · {} asset{} · {}",
28290×
                        r.assets.len(),
28300×
                        if r.assets.len() == 1 { "" } else { "s" },
28310×
                        ui::ago(r.created_ms)
2832
                    ))
2833
                );
2834
            }
2835
        }
28361×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
28371×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
28381×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
28391×
            if json {
28400×
                println!("{}", serde_json::to_string(&r)?);
28411×
            } else {
28421×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
28431×
            }
2844
        }
28450×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
28460×
            let notes = match notes.as_deref() {
28470×
                Some("-") => Some(body_of(None, Some("-".into()))?),
28480×
                _ => notes,
2849
            };
28500×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
28510×
                bail!("say what to change: --title, --notes or --prerelease");
28520×
            }
28530×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
28540×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
28550×
            if json {
28560×
                println!("{}", serde_json::to_string(&r)?);
28570×
            } else {
28580×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
28590×
            }
2860
        }
28611×
        ReleaseCmd::Upload { tag, files } => {
28621×
            if files.is_empty() {
28630×
                bail!("name the files to attach");
28641×
            }
28651×
            for f in files {
28661×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
28671×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
28681×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
28691×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2870
            }
2871
        }
28721×
        ReleaseCmd::Trust { tag } => {
28731×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
28741×
            if json {
28750×
                println!("{}", c.get_text(&path)?);
28760×
                return Ok(0);
28771×
            }
28781×
            let r: serde_json::Value = c.get(&path)?;
28791×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
28801×
            let mut worst = 0;
28814×
            for ch in r["audit"].as_array().into_iter().flatten() {
28824×
                let v = ch["verdict"].as_str().unwrap_or("");
28834×
                worst = worst.max(match v {
28844×
                    "fail" => 2,
28854×
                    "warn" => 1,
28863×
                    _ => 0,
2887
                });
28884×
                let g = match v {
28894×
                    "pass" => ui::ok("✔"),
28901×
                    "warn" => ui::warn("!"),
28910×
                    _ => ui::bad("✘"),
2892
                };
28934×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2894
            }
28951×
            return Ok(if worst == 2 { 1 } else { 0 });
2896
        }
2897
    }
28982×
    Ok(0)
28994×
}
2900
2901
#[cfg(test)]
2902
mod tests {
2903
2904
    #[test]
29051×
    fn job_timings_and_report_commands_read_plainly() {
2906
        use clap::Parser;
29071×
        let job = hub_api::FlowJob {
29081×
            name: "perf".into(),
29091×
            status: "passed".into(),
29101×
            depends_on: vec![],
29111×
            runner: "earth-1".into(),
29121×
            exit_code: Some(0),
29131×
            error: String::new(),
29141×
            started_ms: Some(13_000),
29151×
            finished_ms: Some(200_000),
29161×
            log_lines: 10,
29171×
            waiting: String::new(),
29181×
            placed: String::new(),
29191×
            approval: String::new(),
29201×
            queued_ms: Some(1_000),
29211×
            ready_ms: Some(12_500),
29221×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
29231×
            peak_disk_mib: Some(2150),
29241×
            peak_memory_mib: Some(900),
29251×
        };
29261×
        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");
29271×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
29281×
        assert_eq!(super::timing_line(&bare), "");
29291×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2930
29311×
        let cli =
29321×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
29331×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
29341×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
29351×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
29361×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
29371×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
29381×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
29391×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
29401×
    }
2941
2942
    #[test]
29431×
    fn runner_update_scopes_resolve_by_name_or_id() {
29441×
        let all = hub_api::RunnerUpdates {
29451×
            repo: String::new(),
29461×
            settings: vec![],
29471×
            groups: vec![hub_api::RunnerGroup {
29481×
                id: 4,
29491×
                owner: "acme".into(),
29501×
                name: "canary".into(),
29511×
                percent: None,
29521×
                members: vec![],
29531×
                wave: None,
29541×
            }],
29551×
            runners: vec![],
29561×
            holds: vec![],
29571×
        };
29581×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
29591×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
29603×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
29613×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2962
        }
29631×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
29641×
        assert!(update_scope("everyone", &all).is_err());
29651×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
29661×
        assert!(switch(Some("yes")).is_err());
29671×
    }
2968
    use super::*;
2969
2970
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2971
    /// help says, and a drop is named by its id or its address.
2972
    #[test]
29731×
    fn drop_commands_parse() {
29741×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
29751×
        match cli.cmd {
29761×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
29771×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
29781×
                assert!(secret);
29791×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2980
            }
29810×
            _ => panic!("not drop create"),
2982
        }
29831×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
29841×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
29851×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
29861×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
29871×
                assert!(channel.is_none() && dry_run.is_none());
2988
            }
29890×
            _ => panic!("not runner-updates set"),
2990
        }
29911×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
29921×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
29931×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
29940×
            _ => panic!("not drop list"),
2995
        }
29961×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
29971×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
29981×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2999
            }
30000×
            _ => panic!("not drop view"),
3001
        }
30021×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
30034×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
30044×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
3005
        }
30061×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
30071×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
30081×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
30090×
            _ => panic!("not drop comment"),
3010
        }
30111×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
30121×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
30131×
        assert!(drop_id("andy/notes").is_err());
30141×
    }
3015
}