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