OXYGENHUB
# 8306eca4e4a3 oxygenhub / crates / oh / src / main.rs
93.5 KiB · Rust · last changed Runner updates in waves: a later wave takes a version once the waves before it proved it; an error stops it (refs andymccall/oxygenflow#84) 8 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 mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
954
                if let Some(w) = g.wave {
955
                    what.push_str(&format!(", wave {w}"));
956
                }
957
                println!(
958
                    "  group {} ({what}): {}",
959
                    ui::strong(&g.name),
960
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
961
                );
962
            }
963
            for r in &all.runners {
964
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
965
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
966
            }
967
        }
968
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
969
            let (scope, key) = update_scope(&scope, &all)?;
970
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
971
                scope: scope.clone(),
972
                key: key.clone(),
973
                ..Default::default()
974
            });
975
            if let Some(u) = switch(updates.as_deref())? {
976
                s.updates = u;
977
            }
978
            if let Some(d) = switch(dry_run.as_deref())? {
979
                s.dry_run = d;
980
            }
981
            if let Some(ch) = channel {
982
                s.channel = Some(ch).filter(|c| c != "inherit");
983
            }
984
            if let Some(w) = window {
985
                s.window = Some(w).filter(|w| w != "inherit");
986
            }
987
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
988
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
989
        }
990
        RunnerUpdatesCmd::Lift { version } => {
991
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
992
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
993
        }
994
    }
995
    Ok(0)
996
}
997
998
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
999
fn drop_id(s: &str) -> Result<String> {
1000
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1001
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
1002
        bail!("{s:?} is not a drop's id or address");
1003
    }
1004
    Ok(id.to_ascii_lowercase())
1005
}
1006
1007
fn drop_line(d: &hub_api::Drop) -> String {
1008
    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() };
1009
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
1010
    format!(
1011
        "{} {} {}{}",
1012
        ui::dim(&d.id),
1013
        ui::strong(&title),
1014
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
1015
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1016
    )
1017
}
1018
1019
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
1020
    match cmd {
1021
        DropCmd::Create { files, secret, description, title } => {
1022
            let mut out = Vec::with_capacity(files.len());
1023
            for f in &files {
1024
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
1025
                let content =
1026
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
1027
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1028
            }
1029
            let new =
1030
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
1031
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
1032
            if json {
1033
                println!("{}", serde_json::to_string(&d)?);
1034
            } else {
1035
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
1036
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1037
            }
1038
        }
1039
        DropCmd::List { user } => {
1040
            let path = match &user {
1041
                Some(u) => format!("/users/{}/drops", enc(u)),
1042
                None => "/drops".to_string(),
1043
            };
1044
            if json {
1045
                println!("{}", c.get_text(&path)?);
1046
                return Ok(0);
1047
            }
1048
            let list: Vec<hub_api::Drop> = c.get(&path)?;
1049
            if list.is_empty() {
1050
                println!("{}", ui::dim("No drops."));
1051
            }
1052
            for d in &list {
1053
                println!("{}", drop_line(d));
1054
            }
1055
        }
1056
        DropCmd::View { id, file } => {
1057
            let path = format!("/drops/{}", drop_id(&id)?);
1058
            if json && file.is_none() {
1059
                println!("{}", c.get_text(&path)?);
1060
                return Ok(0);
1061
            }
1062
            let d: hub_api::Drop = c.get(&path)?;
1063
            if let Some(name) = file {
1064
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
1065
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
1066
                print!("{content}");
1067
                return Ok(0);
1068
            }
1069
            println!("{}", drop_line(&d));
1070
            if !d.description.is_empty() {
1071
                println!("{}", d.description);
1072
            }
1073
            println!("{}", ui::kv("url", &d.url));
1074
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
1075
            for f in &d.files {
1076
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
1077
                match &f.content {
1078
                    Some(text) => {
1079
                        print!("{text}");
1080
                        if !text.ends_with('\n') && !text.is_empty() {
1081
                            println!();
1082
                        }
1083
                    }
1084
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1085
                }
1086
            }
1087
        }
1088
        DropCmd::Delete { id } => {
1089
            let id = drop_id(&id)?;
1090
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
1091
            println!("{} drop {id}", ui::ok("✔ deleted"));
1092
        }
1093
    }
1094
    Ok(0)
1095
}
1096
1097
/// `30d`, `12h`, `90m` in milliseconds.
1098
fn duration_ms(s: &str) -> Result<i64> {
1099
    let s = s.trim();
1100
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
1101
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
1102
    let per = match unit {
1103
        "d" => 86_400_000,
1104
        "h" => 3_600_000,
1105
        "m" => 60_000,
1106
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1107
    };
1108
    if n <= 0 {
1109
        bail!("a grant must last some time");
1110
    }
1111
    Ok(n * per)
1112
}
1113
1114
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1115
    use oxy_core::cert::{Grant, SignedGrant};
1116
    use oxy_core::identity::{Identity, Scope};
1117
    match cmd {
1118
        AgentCmd::Grant { name, scope, lasts } => {
1119
            let home = oxy_core::repo::default_home();
1120
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
1121
                format!(
1122
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
1123
                    home.display()
1124
                )
1125
            })?;
1126
            let me: serde_json::Value = c.get("/user")?;
1127
            let username = me["username"].as_str().context("the hub did not say who you are")?;
1128
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
1129
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
1130
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1131
            let grant = Grant {
1132
                grantor: me_id.hash(),
1133
                subject: format!("agent:{name}@{username}"),
1134
                issuer: hub.hash(),
1135
                scope,
1136
                not_before: (now - 60_000) as u64,
1137
                expires: (now + duration_ms(&lasts)?) as u64,
1138
            };
1139
            let signed = SignedGrant::sign(grant, &me_id, &sk);
1140
            let r: serde_json::Value =
1141
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
1142
            if json {
1143
                println!("{r}");
1144
                return Ok(0);
1145
            }
1146
            println!(
1147
                "{} {} to act for you as {} ({}), until {}",
1148
                ui::ok("✔ granted"),
1149
                ui::strong(&name),
1150
                r["subject"].as_str().unwrap_or(""),
1151
                r["scope"].as_str().unwrap_or(""),
1152
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1153
            );
1154
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
1155
            println!(
1156
                "  {}",
1157
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1158
            );
1159
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
1160
            Ok(0)
1161
        }
1162
        AgentCmd::List => {
1163
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
1164
            if json {
1165
                println!("{}", serde_json::to_string(&grants)?);
1166
                return Ok(0);
1167
            }
1168
            if grants.is_empty() {
1169
                println!("{}", ui::dim("no agent grants"));
1170
            }
1171
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1172
            for g in grants {
1173
                let state = if g["revoked_ms"].is_i64() {
1174
                    ui::bad("revoked")
1175
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
1176
                    ui::dim("ended")
1177
                } else {
1178
                    ui::ok("live")
1179
                };
1180
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
1181
                println!(
1182
                    "#{:<4} {:<8} {} · {} · until {} · {}",
1183
                    g["id"],
1184
                    state,
1185
                    ui::strong(g["subject"].as_str().unwrap_or("")),
1186
                    g["scope"].as_str().unwrap_or(""),
1187
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
1188
                    ui::dim(&used)
1189
                );
1190
            }
1191
            Ok(0)
1192
        }
1193
        AgentCmd::Revoke { id } => {
1194
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
1195
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
1196
            Ok(0)
1197
        }
1198
    }
1199
}
1200
1201
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
1202
    let hub = url.trim_end_matches('/').to_string();
1203
    let token = match token.as_deref() {
1204
        Some("-") => {
1205
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
1206
            let mut line = String::new();
1207
            std::io::stdin().read_line(&mut line)?;
1208
            line.trim().to_string()
1209
        }
1210
        Some(t) => t.to_string(),
1211
        None => device_sign_in(&hub, ca.clone())?,
1212
    };
1213
    if token.is_empty() {
1214
        bail!("no token given");
1215
    }
1216
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
1217
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
1218
    let account = me["username"].as_str().unwrap_or("?");
1219
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
1220
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
1221
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
1222
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
1223
    cfg.default_hub = Some(hub.clone());
1224
    cfg.save()?;
1225
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
1226
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
1227
    Ok(0)
1228
}
1229
1230
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1231
/// it on the web, and the token arrives here.
1232
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
1233
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
1234
    let c = Client::new(&t)?;
1235
    let host = std::fs::read_to_string("/etc/hostname")
1236
        .ok()
1237
        .or_else(|| std::env::var("COMPUTERNAME").ok())
1238
        .map(|h| h.trim().to_string())
1239
        .filter(|h| !h.is_empty());
1240
    let client = match host {
1241
        Some(h) => format!("oh on {h}"),
1242
        None => "oh".to_string(),
1243
    };
1244
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
1245
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
1246
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
1247
    if code != 200 {
1248
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
1249
    }
1250
    let device = v["device_code"].as_str().context("no device code")?.to_string();
1251
    let user = v["user_code"].as_str().unwrap_or("?");
1252
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
1253
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
1254
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
1255
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
1256
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1257
    loop {
1258
        std::thread::sleep(std::time::Duration::from_secs(interval));
1259
        if std::time::Instant::now() > deadline {
1260
            bail!("the code expired before it was approved; run oh auth login again");
1261
        }
1262
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
1263
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
1264
        if code == 200 {
1265
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
1266
        }
1267
        match v["error"].as_str() {
1268
            Some("authorization_pending") => {}
1269
            Some("slow_down") => interval += 5,
1270
            Some("access_denied") => bail!("the sign-in was denied on the web"),
1271
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
1272
            _ => bail!("signing in: HTTP {code}: {body}"),
1273
        }
1274
    }
1275
}
1276
1277
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
1278
    match (body, file) {
1279
        (Some(b), _) => Ok(b),
1280
        (None, Some(f)) if f == "-" => {
1281
            let mut s = String::new();
1282
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1283
            Ok(s)
1284
        }
1285
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
1286
        (None, None) => Ok(String::new()),
1287
    }
1288
}
1289
1290
fn issue_line(i: &Issue) -> String {
1291
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
1292
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
1293
    format!(
1294
        "{glyph} {} {}{}{}",
1295
        ui::dim(&format!("#{}", i.number)),
1296
        i.title,
1297
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
1298
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1299
    )
1300
}
1301
1302
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
1303
    let base = t.repo_path()?;
1304
    match cmd {
1305
        IssueCmd::List { state } => {
1306
            let path = format!("{base}/issues?state={}", enc(&state));
1307
            if json {
1308
                println!("{}", c.get_text(&path)?);
1309
                return Ok(0);
1310
            }
1311
            let list: Vec<Issue> = c.get(&path)?;
1312
            if list.is_empty() {
1313
                println!("{}", ui::dim(&format!("No {state} issues.")));
1314
            }
1315
            for i in &list {
1316
                println!("{}", issue_line(i));
1317
            }
1318
        }
1319
        IssueCmd::View { number } => {
1320
            let path = format!("{base}/issues/{number}");
1321
            if json {
1322
                println!("{}", c.get_text(&path)?);
1323
                return Ok(0);
1324
            }
1325
            let i: Issue = c.get(&path)?;
1326
            println!("{}", issue_line(&i));
1327
            if !i.body.trim().is_empty() {
1328
                println!("\n{}\n", i.body.trim_end());
1329
            }
1330
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
1331
            for cm in comments {
1332
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
1333
            }
1334
            println!("{}", ui::dim(&i.url));
1335
        }
1336
        IssueCmd::Create { title, body, body_file, label, project, column } => {
1337
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
1338
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
1339
            if json {
1340
                println!("{}", serde_json::to_string(&i)?);
1341
            } else {
1342
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1343
            }
1344
            if let Some(n) = project {
1345
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
1346
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
1347
                if !json {
1348
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
1349
                }
1350
            }
1351
        }
1352
        IssueCmd::Close { number, reason } => {
1353
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
1354
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1355
        }
1356
        IssueCmd::Reopen { number } => {
1357
            let i: Issue =
1358
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
1359
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1360
        }
1361
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
1362
            let body = match (&body, &body_file) {
1363
                (None, None) => None,
1364
                _ => Some(body_of(body, body_file)?),
1365
            };
1366
            let labels = if no_labels {
1367
                Some(Vec::new())
1368
            } else if label.is_empty() {
1369
                None
1370
            } else {
1371
                Some(label)
1372
            };
1373
            let assignees = if no_assignees {
1374
                Some(Vec::new())
1375
            } else if assignee.is_empty() {
1376
                None
1377
            } else {
1378
                Some(assignee)
1379
            };
1380
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
1381
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
1382
            }
1383
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
1384
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
1385
            if json {
1386
                println!("{}", serde_json::to_string(&i)?);
1387
            } else {
1388
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1389
            }
1390
        }
1391
        IssueCmd::Label(change) => {
1392
            let path = format!("{base}/issues/{}", change.number);
1393
            let now: Issue = c.get(&path)?;
1394
            let labels = change.apply(&now.labels)?;
1395
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
1396
            let i: Issue = c.send("PATCH", &path, &edit)?;
1397
            if json {
1398
                println!("{}", serde_json::to_string(&i)?);
1399
            } else {
1400
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
1401
            }
1402
        }
1403
        IssueCmd::Comment { number, body } => {
1404
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
1405
            println!("{} commented on #{number}", ui::ok("✔"));
1406
        }
1407
    }
1408
    Ok(0)
1409
}
1410
1411
fn source_name(s: &hub_api::ProposalSource) -> String {
1412
    match s {
1413
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
1414
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
1415
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1416
    }
1417
}
1418
1419
fn proposal_line(p: &Proposal) -> String {
1420
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
1421
    let glyph = match state.as_str() {
1422
        "open" => ui::ok("●"),
1423
        "draft" => ui::dim("◌"),
1424
        "landed" => ui::strong("✔"),
1425
        _ => ui::dim("○"),
1426
    };
1427
    format!(
1428
        "{glyph} {} {} {}{}",
1429
        ui::dim(&format!("#{}", p.number)),
1430
        p.title,
1431
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
1432
        ui::dim(&format!(" · {} · {state}", p.author))
1433
    )
1434
}
1435
1436
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
1437
    let base = t.repo_path()?;
1438
    match cmd {
1439
        ProposalCmd::List { state, limit } => {
1440
            let path = format!("{base}/proposals?state={state}&limit={limit}");
1441
            if json {
1442
                println!("{}", c.get_text(&path)?);
1443
                return Ok(0);
1444
            }
1445
            let list: Vec<Proposal> = c.get(&path)?;
1446
            if list.is_empty() {
1447
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
1448
            }
1449
            for p in &list {
1450
                println!("{}", proposal_line(p));
1451
            }
1452
        }
1453
        ProposalCmd::View { number } => {
1454
            let path = format!("{base}/proposals/{number}");
1455
            if json {
1456
                println!("{}", c.get_text(&path)?);
1457
                return Ok(0);
1458
            }
1459
            let p: Proposal = c.get(&path)?;
1460
            println!("{}", proposal_line(&p));
1461
            if !p.body.trim().is_empty() {
1462
                println!("\n{}\n", p.body.trim_end());
1463
            }
1464
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
1465
            for ch in &p.changes {
1466
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
1467
            }
1468
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
1469
            if p.landable {
1470
                println!("{} can land", ui::ok("✔"));
1471
            } else {
1472
                for b in &p.blockers {
1473
                    println!("{} {b}", ui::bad("✘"));
1474
                }
1475
            }
1476
            if p.conflicted {
1477
                println!("{} landing it would leave conflicts", ui::bad("!"));
1478
            }
1479
            println!("{}", ui::dim(&p.url));
1480
        }
1481
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
1482
            let target = match into {
1483
                Some(i) => i,
1484
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1485
            };
1486
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
1487
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
1488
            if json {
1489
                println!("{}", serde_json::to_string(&p)?);
1490
            } else {
1491
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1492
            }
1493
        }
1494
        ProposalCmd::Edit { number, title, body, body_file } => {
1495
            let body = match (&body, &body_file) {
1496
                (None, None) => None,
1497
                _ => Some(body_of(body, body_file)?),
1498
            };
1499
            if title.is_none() && body.is_none() {
1500
                bail!("say what to change: --title, --body or --body-file");
1501
            }
1502
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
1503
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1504
            if json {
1505
                println!("{}", serde_json::to_string(&p)?);
1506
            } else {
1507
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1508
            }
1509
        }
1510
        ProposalCmd::Label(change) => {
1511
            let path = format!("{base}/proposals/{}", change.number);
1512
            let now: Proposal = c.get(&path)?;
1513
            let labels = change.apply(&now.labels)?;
1514
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
1515
            let p: Proposal = c.send("PATCH", &path, &edit)?;
1516
            if json {
1517
                println!("{}", serde_json::to_string(&p)?);
1518
            } else {
1519
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
1520
            }
1521
        }
1522
        ProposalCmd::Comment { number, body, body_file } => {
1523
            let body = body_of(body, body_file)?;
1524
            if body.trim().is_empty() {
1525
                bail!("give the comment with --body or --body-file");
1526
            }
1527
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1528
            println!("{} commented on #{number}", ui::ok("✔"));
1529
        }
1530
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
1531
            let path = format!("{base}/proposals/{number}/auto-land");
1532
            let p: Proposal =
1533
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
1534
            if json {
1535
                println!("{}", serde_json::to_string(&p)?);
1536
            } else if p.landed.is_some() {
1537
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
1538
            } else if p.auto_land.is_some() {
1539
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
1540
            } else {
1541
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
1542
            }
1543
        }
1544
        ProposalCmd::Land { number, over_checks, .. } => {
1545
            let body = match &over_checks {
1546
                Some(r) => serde_json::json!({ "over_checks": r }),
1547
                None => serde_json::json!({}),
1548
            };
1549
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
1550
            if json {
1551
                println!("{}", serde_json::to_string(&p)?);
1552
            } else {
1553
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
1554
            }
1555
        }
1556
        ProposalCmd::Close { number, message } => {
1557
            if let Some(body) = message {
1558
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1559
            }
1560
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1561
            if json {
1562
                println!("{}", serde_json::to_string(&p)?);
1563
            } else {
1564
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1565
            }
1566
        }
1567
        ProposalCmd::Reopen { number } => {
1568
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1569
            if json {
1570
                println!("{}", serde_json::to_string(&p)?);
1571
            } else {
1572
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
1573
            }
1574
        }
1575
        ProposalCmd::Ready { number, undo } => {
1576
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
1577
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1578
            if json {
1579
                println!("{}", serde_json::to_string(&p)?);
1580
            } else if undo {
1581
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
1582
            } else {
1583
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
1584
            }
1585
        }
1586
        ProposalCmd::Checks { number } => {
1587
            let path = format!("{base}/proposals/{number}/checks");
1588
            if json {
1589
                println!("{}", c.get_text(&path)?);
1590
                return Ok(0);
1591
            }
1592
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1593
            if checks.is_empty() {
1594
                println!("{}", ui::dim("No checks yet."));
1595
            }
1596
            for ch in checks {
1597
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1598
            }
1599
        }
1600
    }
1601
    Ok(0)
1602
}
1603
1604
fn run_line(r: &FlowRun) -> String {
1605
    let what =
1606
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1607
    format!(
1608
        "{} {} {} {}",
1609
        ui::status(&r.status),
1610
        ui::dim(&format!("#{}", r.number)),
1611
        what,
1612
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1613
    )
1614
}
1615
1616
fn print_run(r: &FlowRun) {
1617
    println!("{}", run_line(r));
1618
    for j in &r.jobs {
1619
        let dur = match (j.started_ms, j.finished_ms) {
1620
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1621
            _ => String::new(),
1622
        };
1623
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1624
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1625
        // Why a queued job no runner can take waits (oxygenhub#28), and
1626
        // why a job ran where it did (oxygenflow#42).
1627
        if j.status == "queued" && !j.waiting.is_empty() {
1628
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1629
        } else if !j.placed.is_empty() {
1630
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1631
        }
1632
    }
1633
    if !r.error.is_empty() {
1634
        println!("{}", ui::bad(&r.error));
1635
    }
1636
    println!("{}", ui::dim(&r.url));
1637
}
1638
1639
fn live(status: &str) -> bool {
1640
    matches!(status, "queued" | "running")
1641
}
1642
1643
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
1644
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
1645
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
1646
    if json {
1647
        println!("{done}");
1648
    } else {
1649
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
1650
    }
1651
    Ok(())
1652
}
1653
1654
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
1655
    let path = format!("{base}/flow/runs/{number}");
1656
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1657
    loop {
1658
        let r: FlowRun = c.get(&path)?;
1659
        if !json {
1660
            for j in &r.jobs {
1661
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1662
                if seen.get(&j.name) != Some(&shown) {
1663
                    println!("{} {}", ui::status(&j.status), j.name);
1664
                    if j.status == "queued" && !j.waiting.is_empty() {
1665
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1666
                    }
1667
                    seen.insert(j.name.clone(), shown);
1668
                }
1669
            }
1670
        }
1671
        if !live(&r.status) {
1672
            if json {
1673
                println!("{}", serde_json::to_string(&r)?);
1674
            } else {
1675
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1676
            }
1677
            return Ok(if r.status == "passed" { 0 } else { 1 });
1678
        }
1679
        std::thread::sleep(Duration::from_secs(3));
1680
    }
1681
}
1682
1683
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1684
    let base = t.repo_path()?;
1685
    match cmd {
1686
        RunCmd::List { limit } => {
1687
            let path = format!("{base}/flow/runs?limit={limit}");
1688
            if json {
1689
                println!("{}", c.get_text(&path)?);
1690
                return Ok(0);
1691
            }
1692
            let runs: Vec<FlowRun> = c.get(&path)?;
1693
            if runs.is_empty() {
1694
                println!("{}", ui::dim("No runs yet."));
1695
            }
1696
            for r in &runs {
1697
                println!("{}", run_line(r));
1698
            }
1699
        }
1700
        RunCmd::View { number } => {
1701
            let path = format!("{base}/flow/runs/{number}");
1702
            if json {
1703
                println!("{}", c.get_text(&path)?);
1704
                return Ok(0);
1705
            }
1706
            print_run(&c.get(&path)?);
1707
        }
1708
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
1709
            let mut body = match (bookmark, change) {
1710
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1711
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1712
                (None, None) => serde_json::json!({}),
1713
            };
1714
            if !jobs.is_empty() {
1715
                body["jobs"] = serde_json::json!(jobs);
1716
            }
1717
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1718
            let n = started["number"].as_i64().context("the hub named no run")?;
1719
            if !json || !follow {
1720
                if json {
1721
                    println!("{started}");
1722
                } else {
1723
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1724
                }
1725
            }
1726
            if follow {
1727
                return watch(c, &base, n, json);
1728
            }
1729
        }
1730
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1731
        RunCmd::Log { number, job } => {
1732
            let mut after = 0;
1733
            loop {
1734
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1735
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1736
                if lines.is_empty() {
1737
                    break;
1738
                }
1739
                for l in &lines {
1740
                    if json {
1741
                        println!("{}", serde_json::to_string(l)?);
1742
                    } else if l.stream == "flow" {
1743
                        println!("{}", ui::dim(&l.text));
1744
                    } else {
1745
                        println!("{}", l.text);
1746
                    }
1747
                }
1748
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1749
            }
1750
        }
1751
        RunCmd::Rerun { number, job: Some(job) } => {
1752
            let queued: serde_json::Value =
1753
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
1754
            if json {
1755
                println!("{queued}");
1756
            } else {
1757
                let n = queued["queued"].as_i64().unwrap_or(1);
1758
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
1759
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1760
            }
1761
        }
1762
        RunCmd::Rerun { number, job: None } => {
1763
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1764
            if json {
1765
                println!("{started}");
1766
            } else {
1767
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
1768
            }
1769
        }
1770
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
1771
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
1772
        RunCmd::Cancel { number } => {
1773
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
1774
            if json {
1775
                println!("{done}");
1776
            } else {
1777
                println!("{} cancelled run #{number}", ui::ok("✔"));
1778
            }
1779
        }
1780
    }
1781
    Ok(0)
1782
}
1783
1784
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
1785
    let base = t.repo_path()?;
1786
    match cmd {
1787
        LabelCmd::List => {
1788
            let path = format!("{base}/labels");
1789
            if json {
1790
                println!("{}", c.get_text(&path)?);
1791
                return Ok(0);
1792
            }
1793
            let labels: Vec<hub_api::Label> = c.get(&path)?;
1794
            if labels.is_empty() {
1795
                println!("{}", ui::dim("No labels."));
1796
            }
1797
            for l in labels {
1798
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
1799
            }
1800
        }
1801
        LabelCmd::Create { name, colour, description } => {
1802
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
1803
            if json {
1804
                println!("{}", serde_json::to_string(&l)?);
1805
            } else {
1806
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
1807
            }
1808
        }
1809
        LabelCmd::Delete { name } => {
1810
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
1811
            println!("{} deleted label {name}", ui::ok("✔"));
1812
        }
1813
    }
1814
    Ok(0)
1815
}
1816
1817
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
1818
    let base = match (&org, site) {
1819
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
1820
        (None, true) => "/admin/assistants".to_string(),
1821
        (None, false) => format!("{}/assistants", t.repo_path()?),
1822
    };
1823
    match cmd {
1824
        AssistantCmd::List => {
1825
            if json {
1826
                println!("{}", c.get_text(&base)?);
1827
                return Ok(0);
1828
            }
1829
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
1830
            if list.is_empty() {
1831
                println!("{}", ui::dim("No assistants."));
1832
            }
1833
            for a in list {
1834
                let state = if a.enabled && !a.off_above {
1835
                    ui::ok("on")
1836
                } else if a.off_above {
1837
                    ui::dim("off above")
1838
                } else {
1839
                    ui::dim("off")
1840
                };
1841
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
1842
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1843
            }
1844
        }
1845
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
1846
            let token = match token_env {
1847
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
1848
                None => String::new(),
1849
            };
1850
            let body =
1851
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
1852
            let r: serde_json::Value = c.send("POST", &base, &body)?;
1853
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1854
        }
1855
        AssistantCmd::Remove { name } => {
1856
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
1857
            println!("{} removed {name}", ui::ok("✔"));
1858
        }
1859
        AssistantCmd::Prompt { set } => {
1860
            let p: hub_api::AssistantPrompt = match set {
1861
                Some(path) => {
1862
                    let text = if path.as_os_str() == "-" {
1863
                        let mut s = String::new();
1864
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1865
                        s
1866
                    } else {
1867
                        std::fs::read_to_string(&path)?
1868
                    };
1869
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1870
                }
1871
                None => c.get(&format!("{base}/prompt"))?,
1872
            };
1873
            if json {
1874
                println!("{}", serde_json::to_string(&p)?);
1875
                return Ok(0);
1876
            }
1877
            for (from, text) in &p.inherited {
1878
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
1879
            }
1880
            if p.prompt.is_empty() {
1881
                println!("{}", ui::dim("No prompt of its own."));
1882
            } else {
1883
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
1884
            }
1885
        }
1886
    }
1887
    Ok(0)
1888
}
1889
1890
fn project_line(p: &hub_api::Project) -> String {
1891
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
1892
    let private = if p.public { "" } else { " · private" };
1893
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
1894
}
1895
1896
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
1897
    let owner = match owner {
1898
        Some(o) => o,
1899
        None => t.repo()?.0.to_string(),
1900
    };
1901
    let base = format!("/projects/{}", enc(&owner));
1902
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
1903
        let p: hub_api::Project =
1904
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
1905
        if json {
1906
            println!("{}", serde_json::to_string(&p)?);
1907
        } else {
1908
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
1909
        }
1910
        Ok(())
1911
    };
1912
    match cmd {
1913
        ProjectCmd::List => {
1914
            if json {
1915
                println!("{}", c.get_text(&base)?);
1916
                return Ok(0);
1917
            }
1918
            let list: Vec<hub_api::Project> = c.get(&base)?;
1919
            if list.is_empty() {
1920
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
1921
            }
1922
            for p in &list {
1923
                println!("{}", project_line(p));
1924
            }
1925
        }
1926
        ProjectCmd::View { number, archived } => {
1927
            let path = format!("{base}/{number}");
1928
            let cards = format!("{path}/cards?archived=true");
1929
            if json {
1930
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
1931
                return Ok(0);
1932
            }
1933
            let mut b: hub_api::Board = c.get(&path)?;
1934
            if archived {
1935
                b.columns = c.get(&cards)?;
1936
            }
1937
            println!("{}", project_line(&b.project));
1938
            if !b.project.description.is_empty() {
1939
                println!("{}", b.project.description);
1940
            }
1941
            for col in &b.columns {
1942
                println!();
1943
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
1944
                if col.cards.is_empty() {
1945
                    println!("  {}", ui::dim("(empty)"));
1946
                }
1947
                for card in &col.cards {
1948
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
1949
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
1950
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
1951
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
1952
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
1953
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
1954
                }
1955
            }
1956
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1957
        }
1958
        ProjectCmd::Create { title, description, private } => {
1959
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
1960
            if json {
1961
                println!("{}", serde_json::to_string(&p)?);
1962
            } else {
1963
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
1964
            }
1965
        }
1966
        ProjectCmd::Close { number } => state(number, true, "closed")?,
1967
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
1968
        ProjectCmd::Transfer { number, to } => {
1969
            let p: hub_api::Project =
1970
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
1971
            if json {
1972
                println!("{}", serde_json::to_string(&p)?);
1973
            } else {
1974
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
1975
            }
1976
        }
1977
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1978
            // The hub names a card's issue as `repo#N` among the owner's
1979
            // repositories.
1980
            let reference = match reference {
1981
                None => String::new(),
1982
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
1983
                    Some((o, rest)) if o == owner => rest.to_string(),
1984
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
1985
                    None => r,
1986
                },
1987
                Some(r) => {
1988
                    let n = r.trim_start_matches('#');
1989
                    if n.parse::<i64>().is_err() {
1990
                        bail!("{r}: give an issue or proposal number, or NAME#N");
1991
                    }
1992
                    format!("{}#{n}", t.repo()?.1)
1993
                }
1994
            };
1995
            let note = note.unwrap_or_default();
1996
            if reference.is_empty() && note.is_empty() {
1997
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
1998
            }
1999
            let card: hub_api::ProjectCard =
2000
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
2001
            if json {
2002
                println!("{}", serde_json::to_string(&card)?);
2003
            } else {
2004
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2005
            }
2006
        }
2007
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
2008
            (Some(card), None) => {
2009
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
2010
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2011
            }
2012
            (None, Some(from)) => {
2013
                let r: hub_api::CardsMoved = c.send(
2014
                    "POST",
2015
                    &format!("{base}/{number}/cards/move"),
2016
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
2017
                )?;
2018
                if json {
2019
                    println!("{}", serde_json::to_string(&r)?);
2020
                    return Ok(0);
2021
                }
2022
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
2023
                for m in &r.moved {
2024
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2025
                }
2026
                let verb = if dry_run { "would move" } else { "moved" };
2027
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2028
            }
2029
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2030
        },
2031
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
2032
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
2033
                None => None,
2034
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2035
            };
2036
            let r: hub_api::CardsArchived = c.send(
2037
                "POST",
2038
                &format!("{base}/{number}/cards/archive"),
2039
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
2040
            )?;
2041
            if json {
2042
                println!("{}", serde_json::to_string(&r)?);
2043
                return Ok(0);
2044
            }
2045
            let verb = if dry_run { "would archive" } else { "archived" };
2046
            for a in &r.archived {
2047
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
2048
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2049
            }
2050
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2051
        }
2052
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
2053
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
2054
            println!("{} card {card} restored", ui::ok("✔"));
2055
        }
2056
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
2057
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
2058
            println!("{} card {card} removed", ui::ok("✔"));
2059
        }
2060
    }
2061
    Ok(0)
2062
}
2063
2064
fn milestone_line(m: &hub_api::Milestone) -> String {
2065
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
2066
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
2067
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
2068
}
2069
2070
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
2071
    let base = t.repo_path()?;
2072
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
2073
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
2074
        if json {
2075
            println!("{}", serde_json::to_string(&m)?);
2076
        } else {
2077
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
2078
        }
2079
        Ok(())
2080
    };
2081
    match cmd {
2082
        MilestoneCmd::List => {
2083
            let path = format!("{base}/milestones");
2084
            if json {
2085
                println!("{}", c.get_text(&path)?);
2086
                return Ok(0);
2087
            }
2088
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
2089
            if list.is_empty() {
2090
                println!("{}", ui::dim("No milestones."));
2091
            }
2092
            for m in &list {
2093
                println!("{}", milestone_line(m));
2094
            }
2095
        }
2096
        MilestoneCmd::Create { title, description, due } => {
2097
            let m: hub_api::Milestone =
2098
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
2099
            if json {
2100
                println!("{}", serde_json::to_string(&m)?);
2101
            } else {
2102
                println!("{} milestone {}", ui::ok("✔"), m.title);
2103
            }
2104
        }
2105
        MilestoneCmd::Edit { title, rename, description, due } => {
2106
            if rename.is_none() && description.is_none() && due.is_none() {
2107
                bail!("say what to change: --rename, --description or --due");
2108
            }
2109
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2110
        }
2111
        MilestoneCmd::Close { title } => {
2112
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2113
        }
2114
        MilestoneCmd::Reopen { title } => {
2115
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2116
        }
2117
    }
2118
    Ok(0)
2119
}
2120
2121
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
2122
    let base = t.repo_path()?;
2123
    match cmd {
2124
        TagCmd::List => {
2125
            let path = format!("{base}/tags");
2126
            if json {
2127
                println!("{}", c.get_text(&path)?);
2128
                return Ok(0);
2129
            }
2130
            let tags: Vec<Tag> = c.get(&path)?;
2131
            if tags.is_empty() {
2132
                println!("{}", ui::dim("no tags"));
2133
            }
2134
            for t in tags {
2135
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
2136
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
2137
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2138
            }
2139
        }
2140
        TagCmd::Create { name, target, message } => {
2141
            let new = hub_api::NewTag { name, target, message };
2142
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
2143
            if json {
2144
                println!("{}", serde_json::to_string(&made)?);
2145
            } else {
2146
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
2147
            }
2148
        }
2149
        TagCmd::Delete { name, reason } => {
2150
            let reason = reason.unwrap_or_default();
2151
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
2152
            if json {
2153
                println!("{}", serde_json::json!({ "withdrawn": name }));
2154
            } else {
2155
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
2156
            }
2157
        }
2158
    }
2159
    Ok(0)
2160
}
2161
2162
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
2163
    let base = t.repo_path()?;
2164
    match cmd {
2165
        ReleaseCmd::List => {
2166
            let path = format!("{base}/releases");
2167
            if json {
2168
                println!("{}", c.get_text(&path)?);
2169
                return Ok(0);
2170
            }
2171
            let list: Vec<Release> = c.get(&path)?;
2172
            if list.is_empty() {
2173
                println!("{}", ui::dim("No releases."));
2174
            }
2175
            for r in &list {
2176
                println!(
2177
                    "{} {} {}{}",
2178
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
2179
                    ui::strong(&r.tag),
2180
                    r.title,
2181
                    ui::dim(&format!(
2182
                        " · {} asset{} · {}",
2183
                        r.assets.len(),
2184
                        if r.assets.len() == 1 { "" } else { "s" },
2185
                        ui::ago(r.created_ms)
2186
                    ))
2187
                );
2188
            }
2189
        }
2190
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
2191
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
2192
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
2193
            if json {
2194
                println!("{}", serde_json::to_string(&r)?);
2195
            } else {
2196
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2197
            }
2198
        }
2199
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
2200
            let notes = match notes.as_deref() {
2201
                Some("-") => Some(body_of(None, Some("-".into()))?),
2202
                _ => notes,
2203
            };
2204
            if title.is_none() && notes.is_none() && prerelease.is_none() {
2205
                bail!("say what to change: --title, --notes or --prerelease");
2206
            }
2207
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
2208
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
2209
            if json {
2210
                println!("{}", serde_json::to_string(&r)?);
2211
            } else {
2212
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2213
            }
2214
        }
2215
        ReleaseCmd::Upload { tag, files } => {
2216
            if files.is_empty() {
2217
                bail!("name the files to attach");
2218
            }
2219
            for f in files {
2220
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
2221
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
2222
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
2223
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2224
            }
2225
        }
2226
        ReleaseCmd::Trust { tag } => {
2227
            let path = format!("{base}/releases/trust/{}", enc(&tag));
2228
            if json {
2229
                println!("{}", c.get_text(&path)?);
2230
                return Ok(0);
2231
            }
2232
            let r: serde_json::Value = c.get(&path)?;
2233
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
2234
            let mut worst = 0;
2235
            for ch in r["audit"].as_array().into_iter().flatten() {
2236
                let v = ch["verdict"].as_str().unwrap_or("");
2237
                worst = worst.max(match v {
2238
                    "fail" => 2,
2239
                    "warn" => 1,
2240
                    _ => 0,
2241
                });
2242
                let g = match v {
2243
                    "pass" => ui::ok("✔"),
2244
                    "warn" => ui::warn("!"),
2245
                    _ => ui::bad("✘"),
2246
                };
2247
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2248
            }
2249
            return Ok(if worst == 2 { 1 } else { 0 });
2250
        }
2251
    }
2252
    Ok(0)
2253
}
2254
2255
#[cfg(test)]
2256
mod tests {
2257
2258
    #[test]
2259
    fn runner_update_scopes_resolve_by_name_or_id() {
2260
        let all = hub_api::RunnerUpdates {
2261
            repo: String::new(),
2262
            settings: vec![],
2263
            groups: vec![hub_api::RunnerGroup {
2264
                id: 4,
2265
                owner: "acme".into(),
2266
                name: "canary".into(),
2267
                percent: None,
2268
                members: vec![],
2269
                wave: None,
2270
            }],
2271
            runners: vec![],
2272
            holds: vec![],
2273
        };
2274
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
2275
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
2276
        for g in ["group:canary", "group:acme/canary", "group:4"] {
2277
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2278
        }
2279
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
2280
        assert!(update_scope("everyone", &all).is_err());
2281
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
2282
        assert!(switch(Some("yes")).is_err());
2283
    }
2284
    use super::*;
2285
2286
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2287
    /// help says, and a drop is named by its id or its address.
2288
    #[test]
2289
    fn drop_commands_parse() {
2290
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
2291
        match cli.cmd {
2292
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
2293
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
2294
                assert!(secret);
2295
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2296
            }
2297
            _ => panic!("not drop create"),
2298
        }
2299
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
2300
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
2301
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
2302
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
2303
                assert!(channel.is_none() && dry_run.is_none());
2304
            }
2305
            _ => panic!("not runner-updates set"),
2306
        }
2307
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
2308
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
2309
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
2310
            _ => panic!("not drop list"),
2311
        }
2312
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
2313
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
2314
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2315
            }
2316
            _ => panic!("not drop view"),
2317
        }
2318
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
2319
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
2320
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
2321
        assert!(drop_id("andy/notes").is_err());
2322
    }
2323
}