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