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