OXYGENHUB

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

628 of 1546 lines run, 44 of 231 functions · run #526 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 target;
7
mod ui;
8
9
use anyhow::{bail, Context, Result};
10
use clap::{Parser, Subcommand};
11
use client::Client;
12
use hub_api::{
13
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
14
};
15
use std::time::Duration;
16
use target::{Choice, Config, Target};
17
18
#[derive(Parser)]
19
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
20
struct Cli {
21
    /// The repository, when not inside an Oxygen checkout
22
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
23
    repo: Option<String>,
24
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
25
    #[arg(long, global = true, value_name = "URL")]
26
    hub: Option<String>,
27
    /// Which of the checkout's remotes to use (default: origin, or the only one)
28
    #[arg(long, global = true)]
29
    remote: Option<String>,
30
    /// Machine-readable output: the API's JSON, unchanged
31
    #[arg(long, global = true)]
32
    json: bool,
33
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
34
    #[arg(long, global = true)]
35
    plain: bool,
36
    #[command(subcommand)]
37
    cmd: Cmd,
38
}
39
40
#[derive(Subcommand)]
41
enum Cmd {
42
    /// Sign in to a hub, or show who you are signed in as
43
    Auth {
44
        #[command(subcommand)]
45
        cmd: AuthCmd,
46
    },
47
    /// The repository
48
    Repo {
49
        #[command(subcommand)]
50
        cmd: RepoCmd,
51
    },
52
    /// Issues
53
    Issue {
54
        #[command(subcommand)]
55
        cmd: IssueCmd,
56
    },
57
    /// Proposals (pull requests)
58
    Proposal {
59
        #[command(subcommand)]
60
        cmd: ProposalCmd,
61
    },
62
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
63
    Coverage {
64
        #[command(subcommand)]
65
        cmd: CoverageCmd,
66
    },
67
    /// OxygenFlow runs
68
    Run {
69
        #[command(subcommand)]
70
        cmd: RunCmd,
71
    },
72
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
73
    Report {
74
        #[command(subcommand)]
75
        cmd: ReportCmd,
76
    },
77
    /// Releases
78
    Release {
79
        #[command(subcommand)]
80
        cmd: ReleaseCmd,
81
    },
82
    /// Tags: list, create, withdraw
83
    Tag {
84
        #[command(subcommand)]
85
        cmd: TagCmd,
86
    },
87
    /// The repository's labels
88
    Label {
89
        #[command(subcommand)]
90
        cmd: LabelCmd,
91
    },
92
    /// Milestones: list, create, edit, close
93
    Milestone {
94
        #[command(subcommand)]
95
        cmd: MilestoneCmd,
96
    },
97
    /// Project boards of the repository's owner (or --owner): list,
98
    /// create, view, and cards
99
    Project {
100
        #[command(subcommand)]
101
        cmd: ProjectCmd,
102
        /// A user or organisation other than the repository's owner
103
        #[arg(long, global = true)]
104
        owner: Option<String>,
105
    },
106
    /// AI assistants of the repository (its admins), or with --org or
107
    /// --site of an organisation or the site
108
    Assistant {
109
        #[command(subcommand)]
110
        cmd: AssistantCmd,
111
        /// An organisation's assistants instead of the repository's
112
        #[arg(long, global = true)]
113
        org: Option<String>,
114
        /// The site's assistants (administrators)
115
        #[arg(long, global = true, conflicts_with = "org")]
116
        site: bool,
117
    },
118
    /// Agents that act for you without a key of their own (keyless
119
    /// signing): grant, list, revoke
120
    Agent {
121
        #[command(subcommand)]
122
        cmd: AgentCmd,
123
    },
124
    /// Drops: small snippets of files, each its own repository, never
125
    /// listed among your repositories (oxygenhub#279)
126
    Drop {
127
        #[command(subcommand)]
128
        cmd: DropCmd,
129
    },
130
    /// Runners that update themselves (site administrators; oxygenhub#322):
131
    /// where builds come from, who takes them, what is held back
132
    #[command(name = "runner-updates")]
133
    RunnerUpdates {
134
        #[command(subcommand)]
135
        cmd: Option<RunnerUpdatesCmd>,
136
    },
137
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
138
    Api {
139
        /// A path under /api/v1
140
        path: String,
141
        /// The method
142
        #[arg(long, short = 'X', default_value = "GET")]
143
        method: String,
144
        /// A JSON body
145
        #[arg(long, short = 'd')]
146
        data: Option<String>,
147
    },
148
}
149
150
#[derive(Subcommand)]
151
enum AgentCmd {
152
    /// Let an agent act for you: your oxy key (the one your oxy home names
153
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
154
    /// the agent a token it exchanges for ten-minute certificates. The
155
    /// token is printed once: give it to the agent (`oxy auth grant`)
156
    Grant {
157
        /// The agent's name, as in agent:NAME@YOU
158
        name: String,
159
        /// What its keys may do for you: changes, seal, refs
160
        #[arg(long, default_value = "changes,seal,refs")]
161
        scope: String,
162
        /// How long the grant lasts: 30d, 12h, 90m
163
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
164
        lasts: String,
165
    },
166
    /// Your grants, live and past
167
    List,
168
    /// Stop a grant at once: no more certificates under it
169
    Revoke { id: i64 },
170
}
171
172
#[derive(Subcommand)]
173
enum DropCmd {
174
    /// Make a drop of these files, signed by the hub as your delegate
175
    Create {
176
        /// The files (their names in the drop are their file names)
177
        #[arg(required = true)]
178
        files: Vec<std::path::PathBuf>,
179
        /// Unlisted: readable by anyone with its address, listed nowhere
180
        #[arg(long)]
181
        secret: bool,
182
        /// A description
183
        #[arg(long, short = 'd', value_name = "TEXT")]
184
        description: Option<String>,
185
        /// A title (default: the first file's name)
186
        #[arg(long, short = 't')]
187
        title: Option<String>,
188
    },
189
    /// Your drops, or someone's public ones
190
    List {
191
        /// Whose drops
192
        #[arg(long, short = 'u', value_name = "NAME")]
193
        user: Option<String>,
194
    },
195
    /// A drop's files, printed (by id or address)
196
    View {
197
        /// The drop's id, or its address
198
        id: String,
199
        /// Print only this file's content
200
        #[arg(long, short = 'f', value_name = "NAME")]
201
        file: Option<String>,
202
    },
203
    /// Delete a drop and its history
204
    Delete {
205
        /// The drop's id, or its address
206
        id: String,
207
    },
208
}
209
210
#[derive(Subcommand)]
211
enum RunnerUpdatesCmd {
212
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
213
    Show,
214
    /// Change one level's settings; what is not given stays as it is
215
    Set {
216
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
217
        scope: String,
218
        /// `on`, `off` or `inherit`
219
        #[arg(long)]
220
        updates: Option<String>,
221
        /// `stable`, `canary`, a version, or `inherit`
222
        #[arg(long)]
223
        channel: Option<String>,
224
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
225
        #[arg(long)]
226
        window: Option<String>,
227
        /// `on`, `off` or `inherit`
228
        #[arg(long)]
229
        dry_run: Option<String>,
230
    },
231
    /// Offer a held build again (it rolled back on a runner)
232
    Lift { version: String },
233
}
234
235
#[derive(Subcommand)]
236
enum AuthCmd {
237
    /// Sign in to a hub and make it the default: approve a code on the web
238
    /// (device sign-in), or give a token
239
    Login {
240
        /// The hub, e.g. https://oxygenhub.io
241
        #[arg(long = "with-hub", value_name = "URL")]
242
        url: String,
243
        /// An API token from the hub's Settings → Tokens, instead of
244
        /// approving a code ("-" reads it from stdin)
245
        #[arg(long)]
246
        token: Option<String>,
247
        /// The hub's CA certificate, when self-signed
248
        #[arg(long)]
249
        ca: Option<std::path::PathBuf>,
250
    },
251
    /// Who the token in use belongs to
252
    Status,
253
}
254
255
#[derive(Subcommand)]
256
enum RepoCmd {
257
    /// Name, description, visibility and default bookmark
258
    View,
259
}
260
261
#[derive(Subcommand)]
262
enum IssueCmd {
263
    /// Put labels on an issue or take them off (triage)
264
    Label(LabelChange),
265
    /// Open issues (or --state closed|all)
266
    List {
267
        #[arg(long, default_value = "open")]
268
        state: String,
269
    },
270
    /// One issue with its comments
271
    View { number: i64 },
272
    /// Open an issue
273
    Create {
274
        #[arg(long, short)]
275
        title: String,
276
        #[arg(long, short)]
277
        body: Option<String>,
278
        /// Read the body from a file ("-" for stdin)
279
        #[arg(long, short = 'F')]
280
        body_file: Option<String>,
281
        /// A label (repeatable)
282
        #[arg(long, short)]
283
        label: Vec<String>,
284
        /// Also put it on this board of the repository's owner
285
        #[arg(long, short)]
286
        project: Option<i64>,
287
        /// The board's column for it, by name (default: the first)
288
        #[arg(long, requires = "project")]
289
        column: Option<String>,
290
    },
291
    /// Close an issue
292
    Close {
293
        number: i64,
294
        /// `completed` or `not_planned`
295
        #[arg(long, default_value = "completed")]
296
        reason: String,
297
    },
298
    /// Reopen an issue
299
    Reopen { number: i64 },
300
    /// Change an issue's title or body (its author or triage), or its
301
    /// labels, assignees or milestone as whole sets (triage)
302
    Edit {
303
        number: i64,
304
        #[arg(long, short)]
305
        title: Option<String>,
306
        #[arg(long, short)]
307
        body: Option<String>,
308
        /// Read the body from a file ("-" for stdin)
309
        #[arg(long, short = 'F', conflicts_with = "body")]
310
        body_file: Option<String>,
311
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
312
        #[arg(long, short)]
313
        label: Vec<String>,
314
        /// Clear its labels
315
        #[arg(long, conflicts_with = "label")]
316
        no_labels: bool,
317
        /// The users it should be assigned to (repeatable)
318
        #[arg(long, short)]
319
        assignee: Vec<String>,
320
        /// Take everyone off it
321
        #[arg(long, conflicts_with = "assignee")]
322
        no_assignees: bool,
323
        /// A milestone's title ("" takes it out of its milestone)
324
        #[arg(long, short)]
325
        milestone: Option<String>,
326
    },
327
    /// Comment on an issue
328
    Comment {
329
        number: i64,
330
        #[arg(long, short)]
331
        body: Option<String>,
332
        /// Read the body from a file ("-" for stdin), as proposal comment
333
        /// does (#260)
334
        #[arg(long, short = 'F', conflicts_with = "body")]
335
        body_file: Option<String>,
336
    },
337
}
338
339
#[derive(Subcommand)]
340
enum ProposalCmd {
341
    /// Open proposals (or --state draft|landed|closed|all), newest first
342
    List {
343
        #[arg(long, default_value = "open")]
344
        state: String,
345
        /// At most this many
346
        #[arg(long, default_value_t = 30)]
347
        limit: usize,
348
    },
349
    /// One proposal: its changes, approvals and whether it can land
350
    View { number: i64 },
351
    /// Propose a bookmark's changes for another bookmark
352
    Create {
353
        #[arg(long, short)]
354
        title: String,
355
        #[arg(long, short)]
356
        body: Option<String>,
357
        /// Read the body from a file ("-" for stdin)
358
        #[arg(long, short = 'F', conflicts_with = "body")]
359
        body_file: Option<String>,
360
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
361
        #[arg(long)]
362
        from: String,
363
        /// The bookmark to land them on (default: the repository's default bookmark)
364
        #[arg(long)]
365
        into: Option<String>,
366
        #[arg(long)]
367
        draft: bool,
368
    },
369
    /// Change a proposal's title or description (its author or a maintainer)
370
    Edit {
371
        number: i64,
372
        #[arg(long, short)]
373
        title: Option<String>,
374
        #[arg(long, short)]
375
        body: Option<String>,
376
        /// Read the body from a file ("-" for stdin)
377
        #[arg(long, short = 'F', conflicts_with = "body")]
378
        body_file: Option<String>,
379
    },
380
    /// Put labels on a proposal or take them off (triage)
381
    Label(LabelChange),
382
    /// Comment on a proposal's conversation
383
    Comment {
384
        number: i64,
385
        #[arg(long, short)]
386
        body: Option<String>,
387
        /// Read the comment from a file ("-" for stdin)
388
        #[arg(long, short = 'F', conflicts_with = "body")]
389
        body_file: Option<String>,
390
    },
391
    /// The checks on a proposal's projected state
392
    Checks { number: i64 },
393
    /// Land a proposal on its target, as the page's Land button does
394
    Land {
395
        number: i64,
396
        /// Land before its required checks pass, saying why (maintainers;
397
        /// recorded and audited, #261)
398
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
399
        over_checks: Option<String>,
400
        /// Land it by itself once its checks pass (#261); with --off, don't
401
        #[arg(long)]
402
        when_ready: bool,
403
        /// With --when-ready: turn it off
404
        #[arg(long, requires = "when_ready")]
405
        off: bool,
406
    },
407
    /// Close a proposal without landing it, with an optional comment
408
    Close {
409
        number: i64,
410
        /// Say why, as a comment before it closes
411
        #[arg(long, short = 'm')]
412
        message: Option<String>,
413
    },
414
    /// Reopen a closed proposal
415
    Reopen { number: i64 },
416
    /// Take a draft proposal out of draft, ready for review (its author or triage)
417
    Ready {
418
        number: i64,
419
        /// Turn an open proposal back into a draft instead
420
        #[arg(long)]
421
        undo: bool,
422
    },
423
}
424
425
#[derive(Subcommand)]
426
enum AssistantCmd {
427
    /// The assistants this level sees, its own and those inherited
428
    List,
429
    /// Add an assistant, or change the one of that name
430
    Add {
431
        /// How it shows on reviews (default: the provider's name)
432
        #[arg(long, default_value = "")]
433
        name: String,
434
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
435
        #[arg(long, default_value = "")]
436
        preset: String,
437
        /// The endpoint, when no preset or another one
438
        #[arg(long, default_value = "")]
439
        endpoint: String,
440
        /// chat-completions or anthropic-messages
441
        #[arg(long, default_value = "")]
442
        api: String,
443
        /// One the endpoint lists (`oh assistant models` shows them)
444
        #[arg(long)]
445
        model: String,
446
        /// The API key, read from this environment variable (never typed on the command line)
447
        #[arg(long, value_name = "VAR")]
448
        token_env: Option<String>,
449
        /// Add it turned off
450
        #[arg(long)]
451
        off: bool,
452
    },
453
    /// Remove this level's assistant of that name
454
    Remove { name: String },
455
    /// Show this level's prompt, and those it inherits
456
    Prompt {
457
        /// Set it from this file (`-` for standard input; an empty file clears it)
458
        #[arg(long, value_name = "FILE")]
459
        set: Option<std::path::PathBuf>,
460
    },
461
}
462
463
#[derive(Subcommand)]
464
enum LabelCmd {
465
    /// The repository's labels
466
    List,
467
    /// Create a label, or change the one of that name (triage)
468
    Create {
469
        name: String,
470
        /// `#rrggbb` (default: one the hub picks)
471
        #[arg(long)]
472
        colour: Option<String>,
473
        #[arg(long, short, default_value = "")]
474
        description: String,
475
    },
476
    /// Delete a label, taking it off every issue and proposal (triage)
477
    Delete { name: String },
478
}
479
480
#[derive(Subcommand)]
481
enum ProjectCmd {
482
    /// The owner's boards
483
    List,
484
    /// One board: its columns and cards
485
    View {
486
        number: i64,
487
        /// Its archived cards instead (#293)
488
        #[arg(long)]
489
        archived: bool,
490
    },
491
    /// Create a board (owner, or an organisation's members)
492
    Create {
493
        title: String,
494
        #[arg(long, short, default_value = "")]
495
        description: String,
496
        /// Only the owner (or the organisation's members) can see it
497
        #[arg(long)]
498
        private: bool,
499
    },
500
    /// Close a board
501
    Close { number: i64 },
502
    /// Reopen a board
503
    Reopen { number: i64 },
504
    /// Move a board to another owner you may make boards under (an
505
    /// organisation, say); it takes the next number there
506
    Transfer {
507
        number: i64,
508
        /// The new owner
509
        #[arg(long)]
510
        to: String,
511
    },
512
    /// Cards on a board: add, move, archive, restore, remove
513
    Card {
514
        #[command(subcommand)]
515
        cmd: CardCmd,
516
    },
517
}
518
519
#[derive(Subcommand)]
520
enum CardCmd {
521
    /// Put an issue or proposal on a board (`12` or `#12` in this
522
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
523
    /// or a note with --note
524
    Add {
525
        number: i64,
526
        /// The issue or proposal; a number means this repository's
527
        reference: Option<String>,
528
        /// A note card instead
529
        #[arg(long, conflicts_with = "reference")]
530
        note: Option<String>,
531
        /// The column, by name or id (default: the first)
532
        #[arg(long, short)]
533
        column: Option<String>,
534
    },
535
    /// Move a card to another column (by name or id), or with --from every
536
    /// card of a column at once
537
    Move {
538
        number: i64,
539
        /// The card (its id); leave it out with --from
540
        card: Option<i64>,
541
        #[arg(long, short)]
542
        column: String,
543
        /// Move every card of this column (#289)
544
        #[arg(long, conflicts_with = "card")]
545
        from: Option<String>,
546
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
547
        #[arg(long, value_delimiter = ',', requires = "from")]
548
        except: Vec<String>,
549
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
550
        #[arg(long, value_delimiter = ',', requires = "from")]
551
        state: Vec<String>,
552
        /// With --from: say what would move, and move nothing
553
        #[arg(long, requires = "from")]
554
        dry_run: bool,
555
    },
556
    /// Archive a column's cards: off the board, kept and restorable (#293)
557
    Archive {
558
        number: i64,
559
        /// The column, by name or id
560
        #[arg(long)]
561
        from: String,
562
        /// Only cards that joined the column more than this long ago (14d, or 14)
563
        #[arg(long)]
564
        older: Option<String>,
565
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
566
        #[arg(long, value_delimiter = ',')]
567
        except: Vec<String>,
568
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
569
        #[arg(long, value_delimiter = ',')]
570
        state: Vec<String>,
571
        /// Say what would be archived, and archive nothing
572
        #[arg(long)]
573
        dry_run: bool,
574
    },
575
    /// Put an archived card back at the end of its column
576
    Restore { number: i64, card: i64 },
577
    /// Take a card off a board
578
    Remove { number: i64, card: i64 },
579
}
580
581
#[derive(Subcommand)]
582
enum MilestoneCmd {
583
    /// The repository's milestones
584
    List,
585
    /// Create a milestone, or change the one of that title (triage)
586
    Create {
587
        title: String,
588
        #[arg(long, short, default_value = "")]
589
        description: String,
590
        /// Due date, YYYY-MM-DD
591
        #[arg(long)]
592
        due: Option<String>,
593
    },
594
    /// Change a milestone's title, description or due date (triage)
595
    Edit {
596
        title: String,
597
        #[arg(long, short)]
598
        rename: Option<String>,
599
        #[arg(long, short)]
600
        description: Option<String>,
601
        /// Due date, YYYY-MM-DD ("" for none)
602
        #[arg(long)]
603
        due: Option<String>,
604
    },
605
    /// Close a milestone
606
    Close { title: String },
607
    /// Reopen a milestone
608
    Reopen { title: String },
609
}
610
611
/// Labels to put on or take off an issue or proposal.
612
#[derive(clap::Args)]
613
struct LabelChange {
614
    number: i64,
615
    /// A label to add (repeatable)
616
    #[arg(long, short)]
617
    add: Vec<String>,
618
    /// A label to take off (repeatable)
619
    #[arg(long, short)]
620
    remove: Vec<String>,
621
}
622
623
impl LabelChange {
624
    /// The set after the change, from the one there now.
6250×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6260×
        if self.add.is_empty() && self.remove.is_empty() {
6270×
            bail!("say what to change: --add NAME or --remove NAME");
6280×
        }
6290×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6300×
        for a in &self.add {
6310×
            if !names.contains(a) {
6320×
                names.push(a.clone());
6330×
            }
634
        }
6350×
        Ok(names)
6360×
    }
637
}
638
6390×
fn label_names(labels: &[String]) -> String {
6400×
    if labels.is_empty() {
6410×
        ui::dim("no labels")
642
    } else {
6430×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
644
    }
6450×
}
646
647
#[derive(Subcommand)]
648
enum CoverageCmd {
649
    /// Upload an LCOV or Cobertura report measured on this machine, as the
650
    /// coverage of a bookmark's current state (default: the default
651
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
652
    /// not measured by a runner, and sets no check from it
653
    Upload {
654
        file: std::path::PathBuf,
655
        #[arg(long)]
656
        bookmark: Option<String>,
657
        /// A change's full hash
658
        #[arg(long, conflicts_with = "bookmark")]
659
        change: Option<String>,
660
    },
661
}
662
663
#[derive(Subcommand)]
664
enum RunCmd {
665
    /// Recent runs, newest first
666
    List {
667
        #[arg(long, default_value_t = 20)]
668
        limit: i64,
669
    },
670
    /// A run and its jobs
671
    View {
672
        number: i64,
673
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
674
        #[arg(long)]
675
        timings: bool,
676
    },
677
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
678
    Start {
679
        #[arg(long)]
680
        bookmark: Option<String>,
681
        /// A change's full hash
682
        #[arg(long, conflicts_with = "bookmark")]
683
        change: Option<String>,
684
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
685
        #[arg(long = "job", value_name = "NAME")]
686
        jobs: Vec<String>,
687
        /// Wait for the run and exit 1 unless it passes
688
        #[arg(long)]
689
        watch: bool,
690
    },
691
    /// Follow a run until it finishes; exit 1 unless it passes
692
    Watch { number: i64 },
693
    /// A job's log
694
    Log { number: i64, job: String },
695
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
696
    Report {
697
        number: i64,
698
        job: String,
699
        #[command(flatten)]
700
        pick: ReportPick,
701
    },
702
    /// Run a finished run's state again; with --job, only that job (and the
703
    /// jobs that depend on it) in the same run
704
    Rerun {
705
        number: i64,
706
        #[arg(long)]
707
        job: Option<String>,
708
    },
709
    /// Cancel a run still queued or running; its running jobs are stopped
710
    Cancel { number: i64 },
711
    /// Approve a job that waits for a person (oxygenflow#57)
712
    Approve {
713
        number: i64,
714
        #[arg(long)]
715
        job: String,
716
    },
717
    /// Reject a job that waits for a person: it ends cancelled
718
    Reject {
719
        number: i64,
720
        #[arg(long)]
721
        job: String,
722
    },
723
}
724
725
/// Which report of a job, and what of it to show.
726
#[derive(clap::Args)]
727
struct ReportPick {
728
    /// Which report, when the job published more than one
729
    #[arg(long)]
730
    name: Option<String>,
731
    /// What it holds: its metrics, context and files
732
    #[arg(long, conflicts_with = "file")]
733
    list: bool,
734
    /// One file of it (`data/frames.csv`), as published
735
    #[arg(long, value_name = "PATH")]
736
    file: Option<String>,
737
    /// Write the file here instead of to stdout
738
    #[arg(long, short, value_name = "FILE", requires = "file")]
739
    output: Option<std::path::PathBuf>,
740
}
741
742
#[derive(Subcommand)]
743
enum ReportCmd {
744
    /// The newest run of each report, newest first
745
    List {
746
        /// Only runs on this bookmark
747
        #[arg(long)]
748
        bookmark: Option<String>,
749
    },
750
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
751
    Show {
752
        report: String,
753
        #[arg(long, conflicts_with = "bookmark")]
754
        id: Option<i64>,
755
        #[arg(long)]
756
        bookmark: Option<String>,
757
        /// What it holds: its metrics, context and files
758
        #[arg(long, conflicts_with = "file")]
759
        list: bool,
760
        /// One file of it, as published
761
        #[arg(long, value_name = "PATH")]
762
        file: Option<String>,
763
        /// Write the file here instead of to stdout
764
        #[arg(long, short, value_name = "FILE", requires = "file")]
765
        output: Option<std::path::PathBuf>,
766
    },
767
}
768
769
#[derive(Subcommand)]
770
enum TagCmd {
771
    /// Tags, newest name first
772
    List,
773
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
774
    /// delegate (as `oxy tag create` and a push would be)
775
    Create {
776
        name: String,
777
        /// What to tag (default: the default bookmark)
778
        #[arg(long)]
779
        target: Option<String>,
780
        #[arg(long, short)]
781
        message: Option<String>,
782
    },
783
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
784
    /// their next fetch, and the name is never used again. Refused while a
785
    /// release uses the tag
786
    Delete {
787
        name: String,
788
        /// Why, recorded with the withdrawal
789
        #[arg(long, short)]
790
        reason: Option<String>,
791
    },
792
}
793
794
#[derive(Subcommand)]
795
enum ReleaseCmd {
796
    /// Releases, newest first
797
    List,
798
    /// Create a release on an existing tag
799
    Create {
800
        tag: String,
801
        #[arg(long, short)]
802
        title: Option<String>,
803
        /// Notes in Markdown (default: generated from the changes since the previous release)
804
        #[arg(long, short)]
805
        notes: Option<String>,
806
        #[arg(long)]
807
        prerelease: bool,
808
    },
809
    /// Change a release's title, notes or prerelease flag
810
    Edit {
811
        tag: String,
812
        #[arg(long, short)]
813
        title: Option<String>,
814
        /// New notes in Markdown ("-" reads them from stdin)
815
        #[arg(long, short)]
816
        notes: Option<String>,
817
        /// Mark it a prerelease (true) or not (false)
818
        #[arg(long)]
819
        prerelease: Option<bool>,
820
    },
821
    /// Attach files to a release
822
    Upload { tag: String, files: Vec<std::path::PathBuf> },
823
    /// The release's trust report: signatures, builds, receipts and audit
824
    Trust { tag: String },
825
}
826
82747×
fn main() {
828
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
829
    // other command-line tools do, instead of panicking on the failed
830
    // write (oxygenhub#92).
831
    #[cfg(unix)]
83247×
    unsafe {
83347×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
83447×
    }
83547×
    let cli = Cli::parse();
83647×
    ui::init(cli.plain);
83747×
    match run(cli) {
83840×
        Ok(code) => std::process::exit(code),
8397×
        Err(e) => {
8407×
            eprintln!("{} {e:#}", ui::bad("error:"));
8417×
            std::process::exit(2);
842
        }
843
    }
844
}
845
84619×
fn enc(s: &str) -> String {
84719×
    let mut out = String::new();
84886×
    for b in s.bytes() {
84986×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
85085×
            out.push(b as char);
85185×
        } else {
8521×
            out.push_str(&format!("%{b:02X}"));
8531×
        }
854
    }
85519×
    out
85619×
}
857
85847×
fn run(cli: Cli) -> Result<i32> {
85947×
    let cfg = Config::load()?;
8601×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
8611×
        return login(cfg, url, token.clone(), ca.clone());
86246×
    }
86346×
    let here = std::env::current_dir()?;
86446×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
86545×
    let c = Client::new(&t)?;
86645×
    let json = cli.json;
8670×
    match cli.cmd {
868
        Cmd::Auth { cmd: AuthCmd::Status } => {
8690×
            let me: serde_json::Value = c.get("/user")?;
8700×
            if json {
8710×
                println!("{me}");
8720×
            } else {
8730×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
8740×
            }
8750×
            Ok(0)
876
        }
8770×
        Cmd::Auth { .. } => unreachable!(),
8781×
        Cmd::Api { path, method, data } => {
8791×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
880
            // The method applies with or without a body (#75): without one, a
881
            // GET reads, anything else sends an empty object.
8821×
            let text = match data {
8830×
                Some(d) => c.send_text(
8840×
                    &method.to_uppercase(),
8850×
                    &path,
8860×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
8870×
                )?,
8881×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
8890×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
890
            };
8911×
            println!("{text}");
8921×
            Ok(0)
893
        }
894
        Cmd::Repo { cmd: RepoCmd::View } => {
8951×
            let path = t.repo_path()?;
8961×
            if json {
8970×
                println!("{}", c.get_text(&path)?);
8980×
                return Ok(0);
8991×
            }
9001×
            let r: serde_json::Value = c.get(&path)?;
9011×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
9021×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
9031×
                println!("{d}");
9041×
            }
9051×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
9061×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
9071×
            Ok(0)
908
        }
90915×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
9104×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
9113×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
9120×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
9130×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
9140×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
9150×
            let mut body = serde_json::json!({ "content": content });
9160×
            if let Some(b) = bookmark {
9170×
                body["bookmark"] = b.into();
9180×
            }
9190×
            if let Some(ch) = change {
9200×
                body["change"] = ch.into();
9210×
            }
9220×
            let base = t.repo_path()?;
9230×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
9240×
            if json {
9250×
                println!("{}", serde_json::to_string(&r)?);
926
            } else {
9270×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
9280×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
9290×
                println!(
930
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
9310×
                    ui::ok("✔"),
932
                    r.lines_hit,
933
                    r.lines_found,
934
                    r.files,
9350×
                    ui::dim(&r.url)
936
                );
9370×
                if r.dropped > 0 {
9380×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
9390×
                }
940
            }
9410×
            Ok(0)
942
        }
9434×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
9440×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
9450×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
9460×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
94710×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
9480×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
9490×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
9500×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
9517×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
952
    }
95347×
}
954
955
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
9562×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
9572×
    Ok(match v {
9580×
        None => None,
9592×
        Some("on") => Some(Some(true)),
9602×
        Some("off") => Some(Some(false)),
9612×
        Some("inherit") => Some(None),
9621×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
963
    })
9642×
}
965
966
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
9677×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
9687×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
9691×
    Ok(match kind {
9707×
        "site" if name.is_empty() => ("site".into(), String::new()),
9716×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
9725×
        "group" => {
9733×
            let g = all
9743×
                .groups
9753×
                .iter()
9763×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
9773×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
9783×
            ("group".into(), g.id.to_string())
979
        }
9802×
        "runner" => {
9811×
            let r = all
9821×
                .runners
9831×
                .iter()
9841×
                .find(|r| r.id.to_string() == name || r.name == name)
9851×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
9860×
            ("runner".into(), r.id.to_string())
987
        }
9881×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
989
    })
9907×
}
991
9920×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
9930×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
9940×
    match cmd {
9950×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
996
        RunnerUpdatesCmd::Show => {
9970×
            println!(
998
                "{} {}",
9990×
                ui::strong("Builds from"),
10000×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1001
            );
10020×
            for h in &all.holds {
10030×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
10040×
            }
10050×
            for s in &all.settings {
10060×
                let mut said = vec![];
10070×
                if let Some(u) = s.updates {
10080×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
10090×
                }
10100×
                if let Some(ch) = &s.channel {
10110×
                    said.push(format!("channel {ch}"));
10120×
                }
10130×
                if let Some(w) = &s.window {
10140×
                    said.push(format!("window {w} UTC"));
10150×
                }
10160×
                if let Some(d) = s.dry_run {
10170×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
10180×
                }
10190×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
10200×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1021
            }
10220×
            for g in &all.groups {
10230×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
10240×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
10250×
                if let Some(w) = g.wave {
10260×
                    what.push_str(&format!(", wave {w}"));
10270×
                }
10280×
                println!(
1029
                    "  group {} ({what}): {}",
10300×
                    ui::strong(&g.name),
10310×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1032
                );
1033
            }
10340×
            for r in &all.runners {
10350×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
10360×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1037
            }
1038
        }
10390×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
10400×
            let (scope, key) = update_scope(&scope, &all)?;
10410×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
10420×
                scope: scope.clone(),
10430×
                key: key.clone(),
10440×
                ..Default::default()
10450×
            });
10460×
            if let Some(u) = switch(updates.as_deref())? {
10470×
                s.updates = u;
10480×
            }
10490×
            if let Some(d) = switch(dry_run.as_deref())? {
10500×
                s.dry_run = d;
10510×
            }
10520×
            if let Some(ch) = channel {
10530×
                s.channel = Some(ch).filter(|c| c != "inherit");
10540×
            }
10550×
            if let Some(w) = window {
10560×
                s.window = Some(w).filter(|w| w != "inherit");
10570×
            }
10580×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
10590×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1060
        }
10610×
        RunnerUpdatesCmd::Lift { version } => {
10620×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
10630×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1064
        }
1065
    }
10660×
    Ok(0)
10670×
}
1068
1069
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
10707×
fn drop_id(s: &str) -> Result<String> {
10717×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1072144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
10731×
        bail!("{s:?} is not a drop's id or address");
10746×
    }
10756×
    Ok(id.to_ascii_lowercase())
10767×
}
1077
10782×
fn drop_line(d: &hub_api::Drop) -> String {
10792×
    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() };
10804×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
10812×
    format!(
1082
        "{} {} {}{}",
10832×
        ui::dim(&d.id),
10842×
        ui::strong(&title),
10852×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
10862×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1087
    )
10882×
}
1089
10907×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
10917×
    match cmd {
10921×
        DropCmd::Create { files, secret, description, title } => {
10931×
            let mut out = Vec::with_capacity(files.len());
10942×
            for f in &files {
10952×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
10962×
                let content =
10972×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
10982×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1099
            }
11001×
            let new =
11011×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
11021×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
11031×
            if json {
11041×
                println!("{}", serde_json::to_string(&d)?);
1105
            } else {
11060×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
11070×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1108
            }
1109
        }
11102×
        DropCmd::List { user } => {
11112×
            let path = match &user {
11121×
                Some(u) => format!("/users/{}/drops", enc(u)),
11131×
                None => "/drops".to_string(),
1114
            };
11152×
            if json {
11161×
                println!("{}", c.get_text(&path)?);
11171×
                return Ok(0);
11181×
            }
11191×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
11201×
            if list.is_empty() {
11210×
                println!("{}", ui::dim("No drops."));
11221×
            }
11231×
            for d in &list {
11241×
                println!("{}", drop_line(d));
11251×
            }
1126
        }
11273×
        DropCmd::View { id, file } => {
11283×
            let path = format!("/drops/{}", drop_id(&id)?);
11293×
            if json && file.is_none() {
11300×
                println!("{}", c.get_text(&path)?);
11310×
                return Ok(0);
11323×
            }
11333×
            let d: hub_api::Drop = c.get(&path)?;
11342×
            if let Some(name) = file {
11352×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
11361×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
11371×
                print!("{content}");
11381×
                return Ok(0);
11391×
            }
11401×
            println!("{}", drop_line(&d));
11411×
            if !d.description.is_empty() {
11421×
                println!("{}", d.description);
11431×
            }
11441×
            println!("{}", ui::kv("url", &d.url));
11451×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
11462×
            for f in &d.files {
11472×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
11482×
                match &f.content {
11492×
                    Some(text) => {
11502×
                        print!("{text}");
11512×
                        if !text.ends_with('\n') && !text.is_empty() {
11520×
                            println!();
11532×
                        }
1154
                    }
11550×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1156
                }
1157
            }
1158
        }
11591×
        DropCmd::Delete { id } => {
11601×
            let id = drop_id(&id)?;
11611×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
11621×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1163
        }
1164
    }
11654×
    Ok(0)
11667×
}
1167
1168
/// `30d`, `12h`, `90m` in milliseconds.
11690×
fn duration_ms(s: &str) -> Result<i64> {
11700×
    let s = s.trim();
11710×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
11720×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
11730×
    let per = match unit {
11740×
        "d" => 86_400_000,
11750×
        "h" => 3_600_000,
11760×
        "m" => 60_000,
11770×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1178
    };
11790×
    if n <= 0 {
11800×
        bail!("a grant must last some time");
11810×
    }
11820×
    Ok(n * per)
11830×
}
1184
11850×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1186
    use oxy_core::cert::{Grant, SignedGrant};
1187
    use oxy_core::identity::{Identity, Scope};
11880×
    match cmd {
11890×
        AgentCmd::Grant { name, scope, lasts } => {
11900×
            let home = oxy_core::repo::default_home();
11910×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
11920×
                format!(
1193
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
11940×
                    home.display()
1195
                )
11960×
            })?;
11970×
            let me: serde_json::Value = c.get("/user")?;
11980×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
11990×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
12000×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
12010×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
12020×
            let grant = Grant {
12030×
                grantor: me_id.hash(),
12040×
                subject: format!("agent:{name}@{username}"),
12050×
                issuer: hub.hash(),
12060×
                scope,
12070×
                not_before: (now - 60_000) as u64,
12080×
                expires: (now + duration_ms(&lasts)?) as u64,
1209
            };
12100×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
12110×
            let r: serde_json::Value =
12120×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
12130×
            if json {
12140×
                println!("{r}");
12150×
                return Ok(0);
12160×
            }
12170×
            println!(
1218
                "{} {} to act for you as {} ({}), until {}",
12190×
                ui::ok("✔ granted"),
12200×
                ui::strong(&name),
12210×
                r["subject"].as_str().unwrap_or(""),
12220×
                r["scope"].as_str().unwrap_or(""),
12230×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1224
            );
12250×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
12260×
            println!(
1227
                "  {}",
12280×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1229
            );
12300×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
12310×
            Ok(0)
1232
        }
1233
        AgentCmd::List => {
12340×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
12350×
            if json {
12360×
                println!("{}", serde_json::to_string(&grants)?);
12370×
                return Ok(0);
12380×
            }
12390×
            if grants.is_empty() {
12400×
                println!("{}", ui::dim("no agent grants"));
12410×
            }
12420×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
12430×
            for g in grants {
12440×
                let state = if g["revoked_ms"].is_i64() {
12450×
                    ui::bad("revoked")
12460×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
12470×
                    ui::dim("ended")
1248
                } else {
12490×
                    ui::ok("live")
1250
                };
12510×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
12520×
                println!(
1253
                    "#{:<4} {:<8} {} · {} · until {} · {}",
12540×
                    g["id"],
1255
                    state,
12560×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
12570×
                    g["scope"].as_str().unwrap_or(""),
12580×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
12590×
                    ui::dim(&used)
1260
                );
1261
            }
12620×
            Ok(0)
1263
        }
12640×
        AgentCmd::Revoke { id } => {
12650×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
12660×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
12670×
            Ok(0)
1268
        }
1269
    }
12700×
}
1271
12721×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
12731×
    let hub = url.trim_end_matches('/').to_string();
12741×
    let token = match token.as_deref() {
12751×
        Some("-") => {
12760×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
12770×
            let mut line = String::new();
12780×
            std::io::stdin().read_line(&mut line)?;
12790×
            line.trim().to_string()
1280
        }
12811×
        Some(t) => t.to_string(),
12820×
        None => device_sign_in(&hub, ca.clone())?,
1283
    };
12841×
    if token.is_empty() {
12850×
        bail!("no token given");
12861×
    }
12871×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
12881×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
12891×
    let account = me["username"].as_str().unwrap_or("?");
1290
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
12911×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
12921×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
12931×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
12941×
    cfg.default_hub = Some(hub.clone());
12951×
    cfg.save()?;
12961×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
12971×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
12981×
    Ok(0)
12991×
}
1300
1301
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1302
/// it on the web, and the token arrives here.
13030×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
13040×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
13050×
    let c = Client::new(&t)?;
13060×
    let host = std::fs::read_to_string("/etc/hostname")
13070×
        .ok()
13080×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
13090×
        .map(|h| h.trim().to_string())
13100×
        .filter(|h| !h.is_empty());
13110×
    let client = match host {
13120×
        Some(h) => format!("oh on {h}"),
13130×
        None => "oh".to_string(),
1314
    };
13150×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
13160×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
13170×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
13180×
    if code != 200 {
13190×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
13200×
    }
13210×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
13220×
    let user = v["user_code"].as_str().unwrap_or("?");
13230×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
13240×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
13250×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
13260×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
13270×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1328
    loop {
13290×
        std::thread::sleep(std::time::Duration::from_secs(interval));
13300×
        if std::time::Instant::now() > deadline {
13310×
            bail!("the code expired before it was approved; run oh auth login again");
13320×
        }
13330×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
13340×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
13350×
        if code == 200 {
13360×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
13370×
        }
13380×
        match v["error"].as_str() {
13390×
            Some("authorization_pending") => {}
13400×
            Some("slow_down") => interval += 5,
13410×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
13420×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
13430×
            _ => bail!("signing in: HTTP {code}: {body}"),
1344
        }
1345
    }
13460×
}
1347
13487×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
13497×
    match (body, file) {
13502×
        (Some(b), _) => Ok(b),
13511×
        (None, Some(f)) if f == "-" => {
13520×
            let mut s = String::new();
13530×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
13540×
            Ok(s)
1355
        }
13561×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
13574×
        (None, None) => Ok(String::new()),
1358
    }
13597×
}
1360
13613×
fn issue_line(i: &Issue) -> String {
13623×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
13633×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
13643×
    format!(
1365
        "{glyph} {} {}{}{}",
13663×
        ui::dim(&format!("#{}", i.number)),
1367
        i.title,
13683×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
13693×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1370
    )
13713×
}
1372
137315×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
137415×
    let base = t.repo_path()?;
137515×
    match cmd {
13763×
        IssueCmd::List { state } => {
13773×
            let path = format!("{base}/issues?state={}", enc(&state));
13783×
            if json {
13791×
                println!("{}", c.get_text(&path)?);
13801×
                return Ok(0);
13812×
            }
13822×
            let list: Vec<Issue> = c.get(&path)?;
13832×
            if list.is_empty() {
13841×
                println!("{}", ui::dim(&format!("No {state} issues.")));
13851×
            }
13862×
            for i in &list {
13872×
                println!("{}", issue_line(i));
13882×
            }
1389
        }
13902×
        IssueCmd::View { number } => {
13912×
            let path = format!("{base}/issues/{number}");
13922×
            if json {
13931×
                println!("{}", c.get_text(&path)?);
13941×
                return Ok(0);
13951×
            }
13961×
            let i: Issue = c.get(&path)?;
13971×
            println!("{}", issue_line(&i));
13981×
            if !i.body.trim().is_empty() {
13991×
                println!("\n{}\n", i.body.trim_end());
14001×
            }
14011×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
14022×
            for cm in comments {
14032×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
14042×
            }
14051×
            println!("{}", ui::dim(&i.url));
1406
        }
14073×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
14083×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
14093×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
14102×
            if json {
14110×
                println!("{}", serde_json::to_string(&i)?);
14122×
            } else {
14132×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
14142×
            }
14152×
            if let Some(n) = project {
14161×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
14171×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
14181×
                if !json {
14191×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
14201×
                }
14211×
            }
1422
        }
14231×
        IssueCmd::Close { number, reason } => {
14241×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
14251×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1426
        }
14270×
        IssueCmd::Reopen { number } => {
14280×
            let i: Issue =
14290×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
14300×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1431
        }
14323×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
14333×
            let body = match (&body, &body_file) {
14343×
                (None, None) => None,
14350×
                _ => Some(body_of(body, body_file)?),
1436
            };
14373×
            let labels = if no_labels {
14381×
                Some(Vec::new())
14392×
            } else if label.is_empty() {
14401×
                None
1441
            } else {
14421×
                Some(label)
1443
            };
14443×
            let assignees = if no_assignees {
14451×
                Some(Vec::new())
14462×
            } else if assignee.is_empty() {
14471×
                None
1448
            } else {
14491×
                Some(assignee)
1450
            };
14513×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
14521×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
14532×
            }
14542×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
14552×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
14562×
            if json {
14571×
                println!("{}", serde_json::to_string(&i)?);
14581×
            } else {
14591×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
14601×
            }
1461
        }
14620×
        IssueCmd::Label(change) => {
14630×
            let path = format!("{base}/issues/{}", change.number);
14640×
            let now: Issue = c.get(&path)?;
14650×
            let labels = change.apply(&now.labels)?;
14660×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
14670×
            let i: Issue = c.send("PATCH", &path, &edit)?;
14680×
            if json {
14690×
                println!("{}", serde_json::to_string(&i)?);
14700×
            } else {
14710×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
14720×
            }
1473
        }
14743×
        IssueCmd::Comment { number, body, body_file } => {
14753×
            let body = body_of(body, body_file)?;
14763×
            if body.trim().is_empty() {
14771×
                bail!("give the comment with --body or --body-file");
14782×
            }
14792×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
14802×
            println!("{} commented on #{number}", ui::ok("✔"));
1481
        }
1482
    }
148310×
    Ok(0)
148415×
}
1485
14861×
fn source_name(s: &hub_api::ProposalSource) -> String {
14871×
    match s {
14881×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
14890×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
14900×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1491
    }
14921×
}
1493
14941×
fn proposal_line(p: &Proposal) -> String {
14951×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
14961×
    let glyph = match state.as_str() {
14971×
        "open" => ui::ok("●"),
14980×
        "draft" => ui::dim("◌"),
14990×
        "landed" => ui::strong("✔"),
15000×
        _ => ui::dim("○"),
1501
    };
15021×
    format!(
1503
        "{glyph} {} {} {}{}",
15041×
        ui::dim(&format!("#{}", p.number)),
1505
        p.title,
15061×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
15071×
        ui::dim(&format!(" · {} · {state}", p.author))
1508
    )
15091×
}
1510
15114×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
15124×
    let base = t.repo_path()?;
15134×
    match cmd {
15140×
        ProposalCmd::List { state, limit } => {
15150×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
15160×
            if json {
15170×
                println!("{}", c.get_text(&path)?);
15180×
                return Ok(0);
15190×
            }
15200×
            let list: Vec<Proposal> = c.get(&path)?;
15210×
            if list.is_empty() {
15220×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
15230×
            }
15240×
            for p in &list {
15250×
                println!("{}", proposal_line(p));
15260×
            }
1527
        }
15281×
        ProposalCmd::View { number } => {
15291×
            let path = format!("{base}/proposals/{number}");
15301×
            if json {
15310×
                println!("{}", c.get_text(&path)?);
15320×
                return Ok(0);
15331×
            }
15341×
            let p: Proposal = c.get(&path)?;
15351×
            println!("{}", proposal_line(&p));
15361×
            if !p.body.trim().is_empty() {
15370×
                println!("\n{}\n", p.body.trim_end());
15381×
            }
15391×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
15401×
            for ch in &p.changes {
15411×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
15421×
            }
15431×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
15441×
            if p.landable {
15451×
                println!("{} can land", ui::ok("✔"));
15461×
            } else {
15470×
                for b in &p.blockers {
15480×
                    println!("{} {b}", ui::bad("✘"));
15490×
                }
1550
            }
15511×
            if p.conflicted {
15520×
                println!("{} landing it would leave conflicts", ui::bad("!"));
15531×
            }
15541×
            println!("{}", ui::dim(&p.url));
1555
        }
15561×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
15571×
            let target = match into {
15580×
                Some(i) => i,
15591×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1560
            };
15611×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
15621×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
15631×
            if json {
15640×
                println!("{}", serde_json::to_string(&p)?);
15651×
            } else {
15661×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15671×
            }
1568
        }
15690×
        ProposalCmd::Edit { number, title, body, body_file } => {
15700×
            let body = match (&body, &body_file) {
15710×
                (None, None) => None,
15720×
                _ => Some(body_of(body, body_file)?),
1573
            };
15740×
            if title.is_none() && body.is_none() {
15750×
                bail!("say what to change: --title, --body or --body-file");
15760×
            }
15770×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
15780×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15790×
            if json {
15800×
                println!("{}", serde_json::to_string(&p)?);
15810×
            } else {
15820×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15830×
            }
1584
        }
15850×
        ProposalCmd::Label(change) => {
15860×
            let path = format!("{base}/proposals/{}", change.number);
15870×
            let now: Proposal = c.get(&path)?;
15880×
            let labels = change.apply(&now.labels)?;
15890×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
15900×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
15910×
            if json {
15920×
                println!("{}", serde_json::to_string(&p)?);
15930×
            } else {
15940×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
15950×
            }
1596
        }
15970×
        ProposalCmd::Comment { number, body, body_file } => {
15980×
            let body = body_of(body, body_file)?;
15990×
            if body.trim().is_empty() {
16000×
                bail!("give the comment with --body or --body-file");
16010×
            }
16020×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
16030×
            println!("{} commented on #{number}", ui::ok("✔"));
1604
        }
16050×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
16060×
            let path = format!("{base}/proposals/{number}/auto-land");
16070×
            let p: Proposal =
16080×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
16090×
            if json {
16100×
                println!("{}", serde_json::to_string(&p)?);
16110×
            } else if p.landed.is_some() {
16120×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
16130×
            } else if p.auto_land.is_some() {
16140×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
16150×
            } else {
16160×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
16170×
            }
1618
        }
16192×
        ProposalCmd::Land { number, over_checks, .. } => {
16202×
            let body = match &over_checks {
16210×
                Some(r) => serde_json::json!({ "over_checks": r }),
16222×
                None => serde_json::json!({}),
1623
            };
16242×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
16251×
            if json {
16260×
                println!("{}", serde_json::to_string(&p)?);
16271×
            } else {
16281×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
16291×
            }
1630
        }
16310×
        ProposalCmd::Close { number, message } => {
16320×
            if let Some(body) = message {
16330×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
16340×
            }
16350×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
16360×
            if json {
16370×
                println!("{}", serde_json::to_string(&p)?);
16380×
            } else {
16390×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
16400×
            }
1641
        }
16420×
        ProposalCmd::Reopen { number } => {
16430×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
16440×
            if json {
16450×
                println!("{}", serde_json::to_string(&p)?);
16460×
            } else {
16470×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
16480×
            }
1649
        }
16500×
        ProposalCmd::Ready { number, undo } => {
16510×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
16520×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
16530×
            if json {
16540×
                println!("{}", serde_json::to_string(&p)?);
16550×
            } else if undo {
16560×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
16570×
            } else {
16580×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
16590×
            }
1660
        }
16610×
        ProposalCmd::Checks { number } => {
16620×
            let path = format!("{base}/proposals/{number}/checks");
16630×
            if json {
16640×
                println!("{}", c.get_text(&path)?);
16650×
                return Ok(0);
16660×
            }
16670×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
16680×
            if checks.is_empty() {
16690×
                println!("{}", ui::dim("No checks yet."));
16700×
            }
16710×
            for ch in checks {
16720×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
16730×
            }
1674
        }
1675
    }
16763×
    Ok(0)
16774×
}
1678
16791×
fn run_line(r: &FlowRun) -> String {
16801×
    let what =
16811×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
16821×
    format!(
1683
        "{} {} {} {}",
16841×
        ui::status(&r.status),
16851×
        ui::dim(&format!("#{}", r.number)),
1686
        what,
16871×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1688
    )
16891×
}
1690
16911×
fn print_run(r: &FlowRun, timings: bool) {
16921×
    println!("{}", run_line(r));
16931×
    for j in &r.jobs {
16941×
        let dur = match (j.started_ms, j.finished_ms) {
16950×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
16961×
            _ => String::new(),
1697
        };
16981×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
16991×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1700
        // Why a queued job no runner can take waits (oxygenhub#28), and
1701
        // why a job ran where it did (oxygenflow#42).
17021×
        if j.status == "queued" && !j.waiting.is_empty() {
17030×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
17041×
        } else if !j.placed.is_empty() {
17050×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
17061×
        }
17071×
        if timings {
17080×
            let t = timing_line(j);
17090×
            if !t.is_empty() {
17100×
                println!("    {}", ui::dim(&t));
17110×
            }
17121×
        }
1713
    }
17141×
    if !r.error.is_empty() {
17150×
        println!("{}", ui::bad(&r.error));
17161×
    }
17171×
    println!("{}", ui::dim(&r.url));
17181×
}
1719
1720
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
17213×
fn took(ms: i64) -> String {
17223×
    match ms {
17233×
        ..=999 => format!("{ms} ms"),
17242×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
17251×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1726
    }
17273×
}
1728
1729
/// MiB as a person reads them.
17302×
fn mib(m: i64) -> String {
17312×
    if m >= 1024 {
17321×
        format!("{:.1} GiB", m as f64 / 1024.0)
1733
    } else {
17341×
        format!("{m} MiB")
1735
    }
17362×
}
1737
1738
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1739
/// phase its runner reported, and the most disk and memory it took.
17402×
fn timing_line(j: &FlowJob) -> String {
17412×
    let mut parts = vec![];
17422×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
17431×
        parts.push(format!("waited {}", took((s - q).max(0))));
17441×
    }
17452×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
17462×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
17472×
        .into_iter()
17484×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
17492×
        .collect();
17502×
    if !peaks.is_empty() {
17511×
        parts.push(format!("peak {}", peaks.join(", ")));
17521×
    }
17532×
    parts.join(" · ")
17542×
}
1755
1756
/// A report's path, its segments encoded and its slashes kept.
17571×
fn enc_path(path: &str) -> String {
17581×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
17591×
}
1760
1761
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1762
/// files are at `files(path)`. By default its report.toml; with `list`
1763
/// what it holds; with `file` one file, to stdout or `output`.
17640×
fn show_report(
17650×
    c: &Client,
17660×
    at: &str,
17670×
    files: impl Fn(&str) -> String,
17680×
    list: bool,
17690×
    file: Option<String>,
17700×
    output: Option<std::path::PathBuf>,
17710×
    json: bool,
17720×
) -> Result<()> {
1773
    use std::io::Write;
17740×
    if let Some(path) = file {
17750×
        let bytes = c.get_bytes(&files(&path))?;
17760×
        match output {
17770×
            Some(out) => {
17780×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
17790×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1780
            }
17810×
            None => std::io::stdout().write_all(&bytes)?,
1782
        }
17830×
        return Ok(());
17840×
    }
17850×
    if json {
17860×
        println!("{}", c.get_text(at)?);
17870×
        return Ok(());
17880×
    }
17890×
    if !list {
17900×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
17910×
        return Ok(());
17920×
    }
17930×
    let r: Report = c.get(at)?;
17940×
    print_report(&r);
17950×
    if r.files_expired_ms.is_some() {
17960×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
17970×
    }
17980×
    for f in &r.manifest {
17990×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
18000×
    }
18010×
    println!("{}", ui::dim(&r.url));
18020×
    Ok(())
18030×
}
1804
1805
/// A report's heading, metrics and context.
18060×
fn print_report(r: &Report) {
18070×
    let from = match r.run {
18080×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
18090×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1810
    };
18110×
    println!(
1812
        "{} {} {}",
18130×
        ui::strong(&r.name),
18140×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
18150×
        ui::dim(&format!("· {from} · {} files", r.files))
1816
    );
18170×
    if !r.summary.is_empty() {
18180×
        println!("  {}", r.summary);
18190×
    }
18200×
    for m in &r.metrics {
18210×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
18220×
        let mut notes = vec![];
18230×
        if !m.better.is_empty() {
18240×
            notes.push(format!("{} is better", m.better));
18250×
        }
18260×
        if let Some(a) = m.fail_above {
18270×
            notes.push(format!("fails above {a}"));
18280×
        }
18290×
        if let Some(b) = m.fail_below {
18300×
            notes.push(format!("fails below {b}"));
18310×
        }
18320×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
18330×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1834
    }
18350×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
18360×
        let line: Vec<String> =
18370×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
18380×
        println!("  {}", ui::dim(&line.join(" ")));
18390×
    }
18400×
}
1841
1842
/// `oh report …` (oxygenhub#348).
18430×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
18440×
    let base = t.repo_path()?;
18450×
    match cmd {
18460×
        ReportCmd::List { bookmark } => {
18470×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
18480×
            if json {
18490×
                println!("{}", c.get_text(&path)?);
18500×
                return Ok(0);
18510×
            }
18520×
            let list: Vec<Report> = c.get(&path)?;
18530×
            if list.is_empty() {
18540×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
18550×
            }
18560×
            for r in &list {
18570×
                print_report(r);
18580×
            }
1859
        }
18600×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
18610×
            let at = format!("{base}/reports/{}", enc(&report));
18620×
            let query = match (id, bookmark) {
18630×
                (Some(id), _) => format!("?id={id}"),
18640×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
18650×
                (None, None) => String::new(),
1866
            };
18670×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
18680×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1869
        }
1870
    }
18710×
    Ok(0)
18720×
}
1873
18740×
fn live(status: &str) -> bool {
18750×
    matches!(status, "queued" | "running")
18760×
}
1877
1878
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
18790×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
18800×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
18810×
    if json {
18820×
        println!("{done}");
18830×
    } else {
18840×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
18850×
    }
18860×
    Ok(())
18870×
}
1888
18890×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
18900×
    let path = format!("{base}/flow/runs/{number}");
18910×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1892
    loop {
18930×
        let r: FlowRun = c.get(&path)?;
18940×
        if !json {
18950×
            for j in &r.jobs {
18960×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
18970×
                if seen.get(&j.name) != Some(&shown) {
18980×
                    println!("{} {}", ui::status(&j.status), j.name);
18990×
                    if j.status == "queued" && !j.waiting.is_empty() {
19000×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
19010×
                    }
19020×
                    seen.insert(j.name.clone(), shown);
19030×
                }
1904
            }
19050×
        }
19060×
        if !live(&r.status) {
19070×
            if json {
19080×
                println!("{}", serde_json::to_string(&r)?);
19090×
            } else {
19100×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
19110×
            }
19120×
            return Ok(if r.status == "passed" { 0 } else { 1 });
19130×
        }
19140×
        std::thread::sleep(Duration::from_secs(3));
1915
    }
19160×
}
1917
19183×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
19193×
    let base = t.repo_path()?;
19200×
    match cmd {
19211×
        RunCmd::List { limit } => {
19221×
            let path = format!("{base}/flow/runs?limit={limit}");
19231×
            if json {
19241×
                println!("{}", c.get_text(&path)?);
19251×
                return Ok(0);
19260×
            }
19270×
            let runs: Vec<FlowRun> = c.get(&path)?;
19280×
            if runs.is_empty() {
19290×
                println!("{}", ui::dim("No runs yet."));
19300×
            }
19310×
            for r in &runs {
19320×
                println!("{}", run_line(r));
19330×
            }
1934
        }
19351×
        RunCmd::View { number, timings } => {
19361×
            let path = format!("{base}/flow/runs/{number}");
19371×
            if json {
19380×
                println!("{}", c.get_text(&path)?);
19390×
                return Ok(0);
19401×
            }
19411×
            print_run(&c.get(&path)?, timings);
1942
        }
19431×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
19441×
            let mut body = match (bookmark, change) {
19450×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
19460×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
19471×
                (None, None) => serde_json::json!({}),
1948
            };
19491×
            if !jobs.is_empty() {
19500×
                body["jobs"] = serde_json::json!(jobs);
19511×
            }
19521×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
19531×
            let n = started["number"].as_i64().context("the hub named no run")?;
19541×
            if !json || !follow {
19551×
                if json {
19560×
                    println!("{started}");
19571×
                } else {
19581×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
19591×
                }
19600×
            }
19611×
            if follow {
19620×
                return watch(c, &base, n, json);
19631×
            }
1964
        }
19650×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
19660×
        RunCmd::Log { number, job } => {
19670×
            let mut after = 0;
1968
            loop {
19690×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
19700×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
19710×
                if lines.is_empty() {
19720×
                    break;
19730×
                }
19740×
                for l in &lines {
19750×
                    if json {
19760×
                        println!("{}", serde_json::to_string(l)?);
19770×
                    } else if l.stream == "flow" {
19780×
                        println!("{}", ui::dim(&l.text));
19790×
                    } else {
19800×
                        println!("{}", l.text);
19810×
                    }
1982
                }
19830×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1984
            }
1985
        }
19860×
        RunCmd::Report { number, job, pick } => {
19870×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
19880×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
19890×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
19900×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
1991
        }
19920×
        RunCmd::Rerun { number, job: Some(job) } => {
19930×
            let queued: serde_json::Value =
19940×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
19950×
            if json {
19960×
                println!("{queued}");
19970×
            } else {
19980×
                let n = queued["queued"].as_i64().unwrap_or(1);
19990×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
20000×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2001
            }
2002
        }
20030×
        RunCmd::Rerun { number, job: None } => {
20040×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
20050×
            if json {
20060×
                println!("{started}");
20070×
            } else {
20080×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
20090×
            }
2010
        }
20110×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
20120×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
20130×
        RunCmd::Cancel { number } => {
20140×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
20150×
            if json {
20160×
                println!("{done}");
20170×
            } else {
20180×
                println!("{} cancelled run #{number}", ui::ok("✔"));
20190×
            }
2020
        }
2021
    }
20222×
    Ok(0)
20233×
}
2024
20250×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
20260×
    let base = t.repo_path()?;
20270×
    match cmd {
2028
        LabelCmd::List => {
20290×
            let path = format!("{base}/labels");
20300×
            if json {
20310×
                println!("{}", c.get_text(&path)?);
20320×
                return Ok(0);
20330×
            }
20340×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
20350×
            if labels.is_empty() {
20360×
                println!("{}", ui::dim("No labels."));
20370×
            }
20380×
            for l in labels {
20390×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
20400×
            }
2041
        }
20420×
        LabelCmd::Create { name, colour, description } => {
20430×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
20440×
            if json {
20450×
                println!("{}", serde_json::to_string(&l)?);
20460×
            } else {
20470×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
20480×
            }
2049
        }
20500×
        LabelCmd::Delete { name } => {
20510×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
20520×
            println!("{} deleted label {name}", ui::ok("✔"));
2053
        }
2054
    }
20550×
    Ok(0)
20560×
}
2057
20580×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
20590×
    let base = match (&org, site) {
20600×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
20610×
        (None, true) => "/admin/assistants".to_string(),
20620×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2063
    };
20640×
    match cmd {
2065
        AssistantCmd::List => {
20660×
            if json {
20670×
                println!("{}", c.get_text(&base)?);
20680×
                return Ok(0);
20690×
            }
20700×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
20710×
            if list.is_empty() {
20720×
                println!("{}", ui::dim("No assistants."));
20730×
            }
20740×
            for a in list {
20750×
                let state = if a.enabled && !a.off_above {
20760×
                    ui::ok("on")
20770×
                } else if a.off_above {
20780×
                    ui::dim("off above")
2079
                } else {
20800×
                    ui::dim("off")
2081
                };
20820×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
20830×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2084
            }
2085
        }
20860×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
20870×
            let token = match token_env {
20880×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
20890×
                None => String::new(),
2090
            };
20910×
            let body =
20920×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
20930×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
20940×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2095
        }
20960×
        AssistantCmd::Remove { name } => {
20970×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
20980×
            println!("{} removed {name}", ui::ok("✔"));
2099
        }
21000×
        AssistantCmd::Prompt { set } => {
21010×
            let p: hub_api::AssistantPrompt = match set {
21020×
                Some(path) => {
21030×
                    let text = if path.as_os_str() == "-" {
21040×
                        let mut s = String::new();
21050×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
21060×
                        s
2107
                    } else {
21080×
                        std::fs::read_to_string(&path)?
2109
                    };
21100×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2111
                }
21120×
                None => c.get(&format!("{base}/prompt"))?,
2113
            };
21140×
            if json {
21150×
                println!("{}", serde_json::to_string(&p)?);
21160×
                return Ok(0);
21170×
            }
21180×
            for (from, text) in &p.inherited {
21190×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
21200×
            }
21210×
            if p.prompt.is_empty() {
21220×
                println!("{}", ui::dim("No prompt of its own."));
21230×
            } else {
21240×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
21250×
            }
2126
        }
2127
    }
21280×
    Ok(0)
21290×
}
2130
21312×
fn project_line(p: &hub_api::Project) -> String {
21322×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
21332×
    let private = if p.public { "" } else { " · private" };
21342×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
21352×
}
2136
213710×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
213810×
    let owner = match owner {
21390×
        Some(o) => o,
214010×
        None => t.repo()?.0.to_string(),
2141
    };
214210×
    let base = format!("/projects/{}", enc(&owner));
214310×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
21441×
        let p: hub_api::Project =
21451×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
21461×
        if json {
21470×
            println!("{}", serde_json::to_string(&p)?);
21481×
        } else {
21491×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
21501×
        }
21511×
        Ok(())
21521×
    };
21534×
    match cmd {
2154
        ProjectCmd::List => {
21551×
            if json {
21560×
                println!("{}", c.get_text(&base)?);
21570×
                return Ok(0);
21581×
            }
21591×
            let list: Vec<hub_api::Project> = c.get(&base)?;
21601×
            if list.is_empty() {
21610×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
21621×
            }
21631×
            for p in &list {
21641×
                println!("{}", project_line(p));
21651×
            }
2166
        }
21673×
        ProjectCmd::View { number, archived } => {
21683×
            let path = format!("{base}/{number}");
21693×
            let cards = format!("{path}/cards?archived=true");
21703×
            if json {
21712×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
21722×
                return Ok(0);
21731×
            }
21741×
            let mut b: hub_api::Board = c.get(&path)?;
21751×
            if archived {
21760×
                b.columns = c.get(&cards)?;
21771×
            }
21781×
            println!("{}", project_line(&b.project));
21791×
            if !b.project.description.is_empty() {
21801×
                println!("{}", b.project.description);
21811×
            }
21823×
            for col in &b.columns {
21833×
                println!();
21843×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
21853×
                if col.cards.is_empty() {
21861×
                    println!("  {}", ui::dim("(empty)"));
21872×
                }
21883×
                for card in &col.cards {
21892×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
21902×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
21912×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
21922×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
21932×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
21942×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2195
                }
2196
            }
21971×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2198
        }
21991×
        ProjectCmd::Create { title, description, private } => {
22001×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
22011×
            if json {
22020×
                println!("{}", serde_json::to_string(&p)?);
22031×
            } else {
22041×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
22051×
            }
2206
        }
22071×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
22080×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
22090×
        ProjectCmd::Transfer { number, to } => {
22100×
            let p: hub_api::Project =
22110×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
22120×
            if json {
22130×
                println!("{}", serde_json::to_string(&p)?);
22140×
            } else {
22150×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
22160×
            }
2217
        }
22182×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2219
            // The hub names a card's issue as `repo#N` among the owner's
2220
            // repositories.
22212×
            let reference = match reference {
22221×
                None => String::new(),
22231×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
22240×
                    Some((o, rest)) if o == owner => rest.to_string(),
22250×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
22260×
                    None => r,
2227
                },
22281×
                Some(r) => {
22291×
                    let n = r.trim_start_matches('#');
22301×
                    if n.parse::<i64>().is_err() {
22310×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
22321×
                    }
22331×
                    format!("{}#{n}", t.repo()?.1)
2234
                }
2235
            };
22362×
            let note = note.unwrap_or_default();
22372×
            if reference.is_empty() && note.is_empty() {
22380×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
22392×
            }
22401×
            let card: hub_api::ProjectCard =
22412×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
22421×
            if json {
22430×
                println!("{}", serde_json::to_string(&card)?);
2244
            } else {
22451×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2246
            }
2247
        }
22481×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
22491×
            (Some(card), None) => {
22501×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
22511×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2252
            }
22530×
            (None, Some(from)) => {
22540×
                let r: hub_api::CardsMoved = c.send(
22550×
                    "POST",
22560×
                    &format!("{base}/{number}/cards/move"),
22570×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
22580×
                )?;
22590×
                if json {
22600×
                    println!("{}", serde_json::to_string(&r)?);
22610×
                    return Ok(0);
22620×
                }
22630×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
22640×
                for m in &r.moved {
22650×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2266
                }
22670×
                let verb = if dry_run { "would move" } else { "moved" };
22680×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2269
            }
22700×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2271
        },
22720×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
22730×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
22740×
                None => None,
22750×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2276
            };
22770×
            let r: hub_api::CardsArchived = c.send(
22780×
                "POST",
22790×
                &format!("{base}/{number}/cards/archive"),
22800×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
22810×
            )?;
22820×
            if json {
22830×
                println!("{}", serde_json::to_string(&r)?);
22840×
                return Ok(0);
22850×
            }
22860×
            let verb = if dry_run { "would archive" } else { "archived" };
22870×
            for a in &r.archived {
22880×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
22890×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2290
            }
22910×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2292
        }
22930×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
22940×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
22950×
            println!("{} card {card} restored", ui::ok("✔"));
2296
        }
22971×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
22981×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
22991×
            println!("{} card {card} removed", ui::ok("✔"));
2300
        }
2301
    }
23027×
    Ok(0)
230310×
}
2304
23050×
fn milestone_line(m: &hub_api::Milestone) -> String {
23060×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
23070×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
23080×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
23090×
}
2310
23110×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
23120×
    let base = t.repo_path()?;
23130×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
23140×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
23150×
        if json {
23160×
            println!("{}", serde_json::to_string(&m)?);
23170×
        } else {
23180×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
23190×
        }
23200×
        Ok(())
23210×
    };
23220×
    match cmd {
2323
        MilestoneCmd::List => {
23240×
            let path = format!("{base}/milestones");
23250×
            if json {
23260×
                println!("{}", c.get_text(&path)?);
23270×
                return Ok(0);
23280×
            }
23290×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
23300×
            if list.is_empty() {
23310×
                println!("{}", ui::dim("No milestones."));
23320×
            }
23330×
            for m in &list {
23340×
                println!("{}", milestone_line(m));
23350×
            }
2336
        }
23370×
        MilestoneCmd::Create { title, description, due } => {
23380×
            let m: hub_api::Milestone =
23390×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
23400×
            if json {
23410×
                println!("{}", serde_json::to_string(&m)?);
23420×
            } else {
23430×
                println!("{} milestone {}", ui::ok("✔"), m.title);
23440×
            }
2345
        }
23460×
        MilestoneCmd::Edit { title, rename, description, due } => {
23470×
            if rename.is_none() && description.is_none() && due.is_none() {
23480×
                bail!("say what to change: --rename, --description or --due");
23490×
            }
23500×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2351
        }
23520×
        MilestoneCmd::Close { title } => {
23530×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2354
        }
23550×
        MilestoneCmd::Reopen { title } => {
23560×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2357
        }
2358
    }
23590×
    Ok(0)
23600×
}
2361
23620×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
23630×
    let base = t.repo_path()?;
23640×
    match cmd {
2365
        TagCmd::List => {
23660×
            let path = format!("{base}/tags");
23670×
            if json {
23680×
                println!("{}", c.get_text(&path)?);
23690×
                return Ok(0);
23700×
            }
23710×
            let tags: Vec<Tag> = c.get(&path)?;
23720×
            if tags.is_empty() {
23730×
                println!("{}", ui::dim("no tags"));
23740×
            }
23750×
            for t in tags {
23760×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
23770×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
23780×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2379
            }
2380
        }
23810×
        TagCmd::Create { name, target, message } => {
23820×
            let new = hub_api::NewTag { name, target, message };
23830×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
23840×
            if json {
23850×
                println!("{}", serde_json::to_string(&made)?);
23860×
            } else {
23870×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
23880×
            }
2389
        }
23900×
        TagCmd::Delete { name, reason } => {
23910×
            let reason = reason.unwrap_or_default();
23920×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
23930×
            if json {
23940×
                println!("{}", serde_json::json!({ "withdrawn": name }));
23950×
            } else {
23960×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
23970×
            }
2398
        }
2399
    }
24000×
    Ok(0)
24010×
}
2402
24034×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
24044×
    let base = t.repo_path()?;
24054×
    match cmd {
2406
        ReleaseCmd::List => {
24071×
            let path = format!("{base}/releases");
24081×
            if json {
24091×
                println!("{}", c.get_text(&path)?);
24101×
                return Ok(0);
24110×
            }
24120×
            let list: Vec<Release> = c.get(&path)?;
24130×
            if list.is_empty() {
24140×
                println!("{}", ui::dim("No releases."));
24150×
            }
24160×
            for r in &list {
24170×
                println!(
2418
                    "{} {} {}{}",
24190×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
24200×
                    ui::strong(&r.tag),
2421
                    r.title,
24220×
                    ui::dim(&format!(
2423
                        " · {} asset{} · {}",
24240×
                        r.assets.len(),
24250×
                        if r.assets.len() == 1 { "" } else { "s" },
24260×
                        ui::ago(r.created_ms)
2427
                    ))
2428
                );
2429
            }
2430
        }
24311×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
24321×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
24331×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
24341×
            if json {
24350×
                println!("{}", serde_json::to_string(&r)?);
24361×
            } else {
24371×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
24381×
            }
2439
        }
24400×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
24410×
            let notes = match notes.as_deref() {
24420×
                Some("-") => Some(body_of(None, Some("-".into()))?),
24430×
                _ => notes,
2444
            };
24450×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
24460×
                bail!("say what to change: --title, --notes or --prerelease");
24470×
            }
24480×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
24490×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
24500×
            if json {
24510×
                println!("{}", serde_json::to_string(&r)?);
24520×
            } else {
24530×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
24540×
            }
2455
        }
24561×
        ReleaseCmd::Upload { tag, files } => {
24571×
            if files.is_empty() {
24580×
                bail!("name the files to attach");
24591×
            }
24601×
            for f in files {
24611×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
24621×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
24631×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
24641×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2465
            }
2466
        }
24671×
        ReleaseCmd::Trust { tag } => {
24681×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
24691×
            if json {
24700×
                println!("{}", c.get_text(&path)?);
24710×
                return Ok(0);
24721×
            }
24731×
            let r: serde_json::Value = c.get(&path)?;
24741×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
24751×
            let mut worst = 0;
24764×
            for ch in r["audit"].as_array().into_iter().flatten() {
24774×
                let v = ch["verdict"].as_str().unwrap_or("");
24784×
                worst = worst.max(match v {
24794×
                    "fail" => 2,
24804×
                    "warn" => 1,
24813×
                    _ => 0,
2482
                });
24834×
                let g = match v {
24844×
                    "pass" => ui::ok("✔"),
24851×
                    "warn" => ui::warn("!"),
24860×
                    _ => ui::bad("✘"),
2487
                };
24884×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2489
            }
24901×
            return Ok(if worst == 2 { 1 } else { 0 });
2491
        }
2492
    }
24932×
    Ok(0)
24944×
}
2495
2496
#[cfg(test)]
2497
mod tests {
2498
2499
    #[test]
25001×
    fn job_timings_and_report_commands_read_plainly() {
2501
        use clap::Parser;
25021×
        let job = hub_api::FlowJob {
25031×
            name: "perf".into(),
25041×
            status: "passed".into(),
25051×
            depends_on: vec![],
25061×
            runner: "earth-1".into(),
25071×
            exit_code: Some(0),
25081×
            error: String::new(),
25091×
            started_ms: Some(13_000),
25101×
            finished_ms: Some(200_000),
25111×
            log_lines: 10,
25121×
            waiting: String::new(),
25131×
            placed: String::new(),
25141×
            approval: String::new(),
25151×
            queued_ms: Some(1_000),
25161×
            ready_ms: Some(12_500),
25171×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
25181×
            peak_disk_mib: Some(2150),
25191×
            peak_memory_mib: Some(900),
25201×
        };
25211×
        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");
25221×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
25231×
        assert_eq!(super::timing_line(&bare), "");
25241×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2525
25261×
        let cli =
25271×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
25281×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
25291×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
25301×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
25311×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
25321×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
25331×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
25341×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
25351×
    }
2536
2537
    #[test]
25381×
    fn runner_update_scopes_resolve_by_name_or_id() {
25391×
        let all = hub_api::RunnerUpdates {
25401×
            repo: String::new(),
25411×
            settings: vec![],
25421×
            groups: vec![hub_api::RunnerGroup {
25431×
                id: 4,
25441×
                owner: "acme".into(),
25451×
                name: "canary".into(),
25461×
                percent: None,
25471×
                members: vec![],
25481×
                wave: None,
25491×
            }],
25501×
            runners: vec![],
25511×
            holds: vec![],
25521×
        };
25531×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
25541×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
25553×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
25563×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2557
        }
25581×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
25591×
        assert!(update_scope("everyone", &all).is_err());
25601×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
25611×
        assert!(switch(Some("yes")).is_err());
25621×
    }
2563
    use super::*;
2564
2565
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2566
    /// help says, and a drop is named by its id or its address.
2567
    #[test]
25681×
    fn drop_commands_parse() {
25691×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
25701×
        match cli.cmd {
25711×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
25721×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
25731×
                assert!(secret);
25741×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2575
            }
25760×
            _ => panic!("not drop create"),
2577
        }
25781×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
25791×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
25801×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
25811×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
25821×
                assert!(channel.is_none() && dry_run.is_none());
2583
            }
25840×
            _ => panic!("not runner-updates set"),
2585
        }
25861×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
25871×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
25881×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
25890×
            _ => panic!("not drop list"),
2590
        }
25911×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
25921×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
25931×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2594
            }
25950×
            _ => panic!("not drop view"),
2596
        }
25971×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
25981×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
25991×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
26001×
        assert!(drop_id("andy/notes").is_err());
26011×
    }
2602
}