OXYGENHUB

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

558 of 1366 lines run, 35 of 192 functions · run #518 on main · run missed

1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod target;
7
mod ui;
8
9
use anyhow::{bail, Context, Result};
10
use clap::{Parser, Subcommand};
11
use client::Client;
12
use hub_api::{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.
6180×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6190×
        if self.add.is_empty() && self.remove.is_empty() {
6200×
            bail!("say what to change: --add NAME or --remove NAME");
6210×
        }
6220×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6230×
        for a in &self.add {
6240×
            if !names.contains(a) {
6250×
                names.push(a.clone());
6260×
            }
627
        }
6280×
        Ok(names)
6290×
    }
630
}
631
6320×
fn label_names(labels: &[String]) -> String {
6330×
    if labels.is_empty() {
6340×
        ui::dim("no labels")
635
    } else {
6360×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
637
    }
6380×
}
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
76447×
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)]
76947×
    unsafe {
77047×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
77147×
    }
77247×
    let cli = Cli::parse();
77347×
    ui::init(cli.plain);
77447×
    match run(cli) {
77540×
        Ok(code) => std::process::exit(code),
7767×
        Err(e) => {
7777×
            eprintln!("{} {e:#}", ui::bad("error:"));
7787×
            std::process::exit(2);
779
        }
780
    }
781
}
782
78317×
fn enc(s: &str) -> String {
78417×
    let mut out = String::new();
78567×
    for b in s.bytes() {
78667×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
78767×
            out.push(b as char);
78867×
        } else {
7890×
            out.push_str(&format!("%{b:02X}"));
7900×
        }
791
    }
79217×
    out
79317×
}
794
79547×
fn run(cli: Cli) -> Result<i32> {
79647×
    let cfg = Config::load()?;
7971×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
7981×
        return login(cfg, url, token.clone(), ca.clone());
79946×
    }
80046×
    let here = std::env::current_dir()?;
80146×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
80245×
    let c = Client::new(&t)?;
80345×
    let json = cli.json;
8040×
    match cli.cmd {
805
        Cmd::Auth { cmd: AuthCmd::Status } => {
8060×
            let me: serde_json::Value = c.get("/user")?;
8070×
            if json {
8080×
                println!("{me}");
8090×
            } else {
8100×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
8110×
            }
8120×
            Ok(0)
813
        }
8140×
        Cmd::Auth { .. } => unreachable!(),
8151×
        Cmd::Api { path, method, data } => {
8161×
            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.
8191×
            let text = match data {
8200×
                Some(d) => c.send_text(
8210×
                    &method.to_uppercase(),
8220×
                    &path,
8230×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
8240×
                )?,
8251×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
8260×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
827
            };
8281×
            println!("{text}");
8291×
            Ok(0)
830
        }
831
        Cmd::Repo { cmd: RepoCmd::View } => {
8321×
            let path = t.repo_path()?;
8331×
            if json {
8340×
                println!("{}", c.get_text(&path)?);
8350×
                return Ok(0);
8361×
            }
8371×
            let r: serde_json::Value = c.get(&path)?;
8381×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
8391×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
8401×
                println!("{d}");
8411×
            }
8421×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
8431×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
8441×
            Ok(0)
845
        }
84615×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
8474×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
8483×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
8490×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
8500×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
8510×
            let mut body = serde_json::json!({ "content": content });
8520×
            if let Some(b) = bookmark {
8530×
                body["bookmark"] = b.into();
8540×
            }
8550×
            if let Some(ch) = change {
8560×
                body["change"] = ch.into();
8570×
            }
8580×
            let base = t.repo_path()?;
8590×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
8600×
            if json {
8610×
                println!("{}", serde_json::to_string(&r)?);
862
            } else {
8630×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
8640×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
8650×
                println!(
866
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
8670×
                    ui::ok("✔"),
868
                    r.lines_hit,
869
                    r.lines_found,
870
                    r.files,
8710×
                    ui::dim(&r.url)
872
                );
8730×
                if r.dropped > 0 {
8740×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
8750×
                }
876
            }
8770×
            Ok(0)
878
        }
8794×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
8800×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
8810×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
8820×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
88310×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
8840×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
8850×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
8860×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
8877×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
888
    }
88947×
}
890
891
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
8922×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
8932×
    Ok(match v {
8940×
        None => None,
8952×
        Some("on") => Some(Some(true)),
8962×
        Some("off") => Some(Some(false)),
8972×
        Some("inherit") => Some(None),
8981×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
899
    })
9002×
}
901
902
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
9037×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
9047×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
9051×
    Ok(match kind {
9067×
        "site" if name.is_empty() => ("site".into(), String::new()),
9076×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
9085×
        "group" => {
9093×
            let g = all
9103×
                .groups
9113×
                .iter()
9123×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
9133×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
9143×
            ("group".into(), g.id.to_string())
915
        }
9162×
        "runner" => {
9171×
            let r = all
9181×
                .runners
9191×
                .iter()
9201×
                .find(|r| r.id.to_string() == name || r.name == name)
9211×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
9220×
            ("runner".into(), r.id.to_string())
923
        }
9241×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
925
    })
9267×
}
927
9280×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
9290×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
9300×
    match cmd {
9310×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
932
        RunnerUpdatesCmd::Show => {
9330×
            println!(
934
                "{} {}",
9350×
                ui::strong("Builds from"),
9360×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
937
            );
9380×
            for h in &all.holds {
9390×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
9400×
            }
9410×
            for s in &all.settings {
9420×
                let mut said = vec![];
9430×
                if let Some(u) = s.updates {
9440×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
9450×
                }
9460×
                if let Some(ch) = &s.channel {
9470×
                    said.push(format!("channel {ch}"));
9480×
                }
9490×
                if let Some(w) = &s.window {
9500×
                    said.push(format!("window {w} UTC"));
9510×
                }
9520×
                if let Some(d) = s.dry_run {
9530×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
9540×
                }
9550×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
9560×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
957
            }
9580×
            for g in &all.groups {
9590×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
9600×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
9610×
                if let Some(w) = g.wave {
9620×
                    what.push_str(&format!(", wave {w}"));
9630×
                }
9640×
                println!(
965
                    "  group {} ({what}): {}",
9660×
                    ui::strong(&g.name),
9670×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
968
                );
969
            }
9700×
            for r in &all.runners {
9710×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
9720×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
973
            }
974
        }
9750×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
9760×
            let (scope, key) = update_scope(&scope, &all)?;
9770×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
9780×
                scope: scope.clone(),
9790×
                key: key.clone(),
9800×
                ..Default::default()
9810×
            });
9820×
            if let Some(u) = switch(updates.as_deref())? {
9830×
                s.updates = u;
9840×
            }
9850×
            if let Some(d) = switch(dry_run.as_deref())? {
9860×
                s.dry_run = d;
9870×
            }
9880×
            if let Some(ch) = channel {
9890×
                s.channel = Some(ch).filter(|c| c != "inherit");
9900×
            }
9910×
            if let Some(w) = window {
9920×
                s.window = Some(w).filter(|w| w != "inherit");
9930×
            }
9940×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
9950×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
996
        }
9970×
        RunnerUpdatesCmd::Lift { version } => {
9980×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
9990×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1000
        }
1001
    }
10020×
    Ok(0)
10030×
}
1004
1005
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
10067×
fn drop_id(s: &str) -> Result<String> {
10077×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1008144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
10091×
        bail!("{s:?} is not a drop's id or address");
10106×
    }
10116×
    Ok(id.to_ascii_lowercase())
10127×
}
1013
10142×
fn drop_line(d: &hub_api::Drop) -> String {
10152×
    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() };
10164×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
10172×
    format!(
1018
        "{} {} {}{}",
10192×
        ui::dim(&d.id),
10202×
        ui::strong(&title),
10212×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
10222×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1023
    )
10242×
}
1025
10267×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
10277×
    match cmd {
10281×
        DropCmd::Create { files, secret, description, title } => {
10291×
            let mut out = Vec::with_capacity(files.len());
10302×
            for f in &files {
10312×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
10322×
                let content =
10332×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
10342×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1035
            }
10361×
            let new =
10371×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
10381×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
10391×
            if json {
10401×
                println!("{}", serde_json::to_string(&d)?);
1041
            } else {
10420×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
10430×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1044
            }
1045
        }
10462×
        DropCmd::List { user } => {
10472×
            let path = match &user {
10481×
                Some(u) => format!("/users/{}/drops", enc(u)),
10491×
                None => "/drops".to_string(),
1050
            };
10512×
            if json {
10521×
                println!("{}", c.get_text(&path)?);
10531×
                return Ok(0);
10541×
            }
10551×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
10561×
            if list.is_empty() {
10570×
                println!("{}", ui::dim("No drops."));
10581×
            }
10591×
            for d in &list {
10601×
                println!("{}", drop_line(d));
10611×
            }
1062
        }
10633×
        DropCmd::View { id, file } => {
10643×
            let path = format!("/drops/{}", drop_id(&id)?);
10653×
            if json && file.is_none() {
10660×
                println!("{}", c.get_text(&path)?);
10670×
                return Ok(0);
10683×
            }
10693×
            let d: hub_api::Drop = c.get(&path)?;
10702×
            if let Some(name) = file {
10712×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
10721×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
10731×
                print!("{content}");
10741×
                return Ok(0);
10751×
            }
10761×
            println!("{}", drop_line(&d));
10771×
            if !d.description.is_empty() {
10781×
                println!("{}", d.description);
10791×
            }
10801×
            println!("{}", ui::kv("url", &d.url));
10811×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
10822×
            for f in &d.files {
10832×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
10842×
                match &f.content {
10852×
                    Some(text) => {
10862×
                        print!("{text}");
10872×
                        if !text.ends_with('\n') && !text.is_empty() {
10880×
                            println!();
10892×
                        }
1090
                    }
10910×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1092
                }
1093
            }
1094
        }
10951×
        DropCmd::Delete { id } => {
10961×
            let id = drop_id(&id)?;
10971×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
10981×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1099
        }
1100
    }
11014×
    Ok(0)
11027×
}
1103
1104
/// `30d`, `12h`, `90m` in milliseconds.
11050×
fn duration_ms(s: &str) -> Result<i64> {
11060×
    let s = s.trim();
11070×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
11080×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
11090×
    let per = match unit {
11100×
        "d" => 86_400_000,
11110×
        "h" => 3_600_000,
11120×
        "m" => 60_000,
11130×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1114
    };
11150×
    if n <= 0 {
11160×
        bail!("a grant must last some time");
11170×
    }
11180×
    Ok(n * per)
11190×
}
1120
11210×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1122
    use oxy_core::cert::{Grant, SignedGrant};
1123
    use oxy_core::identity::{Identity, Scope};
11240×
    match cmd {
11250×
        AgentCmd::Grant { name, scope, lasts } => {
11260×
            let home = oxy_core::repo::default_home();
11270×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
11280×
                format!(
1129
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
11300×
                    home.display()
1131
                )
11320×
            })?;
11330×
            let me: serde_json::Value = c.get("/user")?;
11340×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
11350×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
11360×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
11370×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11380×
            let grant = Grant {
11390×
                grantor: me_id.hash(),
11400×
                subject: format!("agent:{name}@{username}"),
11410×
                issuer: hub.hash(),
11420×
                scope,
11430×
                not_before: (now - 60_000) as u64,
11440×
                expires: (now + duration_ms(&lasts)?) as u64,
1145
            };
11460×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
11470×
            let r: serde_json::Value =
11480×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
11490×
            if json {
11500×
                println!("{r}");
11510×
                return Ok(0);
11520×
            }
11530×
            println!(
1154
                "{} {} to act for you as {} ({}), until {}",
11550×
                ui::ok("✔ granted"),
11560×
                ui::strong(&name),
11570×
                r["subject"].as_str().unwrap_or(""),
11580×
                r["scope"].as_str().unwrap_or(""),
11590×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1160
            );
11610×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
11620×
            println!(
1163
                "  {}",
11640×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1165
            );
11660×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
11670×
            Ok(0)
1168
        }
1169
        AgentCmd::List => {
11700×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
11710×
            if json {
11720×
                println!("{}", serde_json::to_string(&grants)?);
11730×
                return Ok(0);
11740×
            }
11750×
            if grants.is_empty() {
11760×
                println!("{}", ui::dim("no agent grants"));
11770×
            }
11780×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11790×
            for g in grants {
11800×
                let state = if g["revoked_ms"].is_i64() {
11810×
                    ui::bad("revoked")
11820×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
11830×
                    ui::dim("ended")
1184
                } else {
11850×
                    ui::ok("live")
1186
                };
11870×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
11880×
                println!(
1189
                    "#{:<4} {:<8} {} · {} · until {} · {}",
11900×
                    g["id"],
1191
                    state,
11920×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
11930×
                    g["scope"].as_str().unwrap_or(""),
11940×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
11950×
                    ui::dim(&used)
1196
                );
1197
            }
11980×
            Ok(0)
1199
        }
12000×
        AgentCmd::Revoke { id } => {
12010×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
12020×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
12030×
            Ok(0)
1204
        }
1205
    }
12060×
}
1207
12081×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
12091×
    let hub = url.trim_end_matches('/').to_string();
12101×
    let token = match token.as_deref() {
12111×
        Some("-") => {
12120×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
12130×
            let mut line = String::new();
12140×
            std::io::stdin().read_line(&mut line)?;
12150×
            line.trim().to_string()
1216
        }
12171×
        Some(t) => t.to_string(),
12180×
        None => device_sign_in(&hub, ca.clone())?,
1219
    };
12201×
    if token.is_empty() {
12210×
        bail!("no token given");
12221×
    }
12231×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
12241×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
12251×
    let account = me["username"].as_str().unwrap_or("?");
1226
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
12271×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
12281×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
12291×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
12301×
    cfg.default_hub = Some(hub.clone());
12311×
    cfg.save()?;
12321×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
12331×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
12341×
    Ok(0)
12351×
}
1236
1237
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1238
/// it on the web, and the token arrives here.
12390×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
12400×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
12410×
    let c = Client::new(&t)?;
12420×
    let host = std::fs::read_to_string("/etc/hostname")
12430×
        .ok()
12440×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
12450×
        .map(|h| h.trim().to_string())
12460×
        .filter(|h| !h.is_empty());
12470×
    let client = match host {
12480×
        Some(h) => format!("oh on {h}"),
12490×
        None => "oh".to_string(),
1250
    };
12510×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
12520×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
12530×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
12540×
    if code != 200 {
12550×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
12560×
    }
12570×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
12580×
    let user = v["user_code"].as_str().unwrap_or("?");
12590×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
12600×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
12610×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
12620×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
12630×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1264
    loop {
12650×
        std::thread::sleep(std::time::Duration::from_secs(interval));
12660×
        if std::time::Instant::now() > deadline {
12670×
            bail!("the code expired before it was approved; run oh auth login again");
12680×
        }
12690×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
12700×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
12710×
        if code == 200 {
12720×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
12730×
        }
12740×
        match v["error"].as_str() {
12750×
            Some("authorization_pending") => {}
12760×
            Some("slow_down") => interval += 5,
12770×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
12780×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
12790×
            _ => bail!("signing in: HTTP {code}: {body}"),
1280
        }
1281
    }
12820×
}
1283
12847×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
12857×
    match (body, file) {
12862×
        (Some(b), _) => Ok(b),
12871×
        (None, Some(f)) if f == "-" => {
12880×
            let mut s = String::new();
12890×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
12900×
            Ok(s)
1291
        }
12921×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
12934×
        (None, None) => Ok(String::new()),
1294
    }
12957×
}
1296
12973×
fn issue_line(i: &Issue) -> String {
12983×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
12993×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
13003×
    format!(
1301
        "{glyph} {} {}{}{}",
13023×
        ui::dim(&format!("#{}", i.number)),
1303
        i.title,
13043×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
13053×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1306
    )
13073×
}
1308
130915×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
131015×
    let base = t.repo_path()?;
131115×
    match cmd {
13123×
        IssueCmd::List { state } => {
13133×
            let path = format!("{base}/issues?state={}", enc(&state));
13143×
            if json {
13151×
                println!("{}", c.get_text(&path)?);
13161×
                return Ok(0);
13172×
            }
13182×
            let list: Vec<Issue> = c.get(&path)?;
13192×
            if list.is_empty() {
13201×
                println!("{}", ui::dim(&format!("No {state} issues.")));
13211×
            }
13222×
            for i in &list {
13232×
                println!("{}", issue_line(i));
13242×
            }
1325
        }
13262×
        IssueCmd::View { number } => {
13272×
            let path = format!("{base}/issues/{number}");
13282×
            if json {
13291×
                println!("{}", c.get_text(&path)?);
13301×
                return Ok(0);
13311×
            }
13321×
            let i: Issue = c.get(&path)?;
13331×
            println!("{}", issue_line(&i));
13341×
            if !i.body.trim().is_empty() {
13351×
                println!("\n{}\n", i.body.trim_end());
13361×
            }
13371×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
13382×
            for cm in comments {
13392×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
13402×
            }
13411×
            println!("{}", ui::dim(&i.url));
1342
        }
13433×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
13443×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
13453×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
13462×
            if json {
13470×
                println!("{}", serde_json::to_string(&i)?);
13482×
            } else {
13492×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13502×
            }
13512×
            if let Some(n) = project {
13521×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
13531×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
13541×
                if !json {
13551×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
13561×
                }
13571×
            }
1358
        }
13591×
        IssueCmd::Close { number, reason } => {
13601×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
13611×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1362
        }
13630×
        IssueCmd::Reopen { number } => {
13640×
            let i: Issue =
13650×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
13660×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1367
        }
13683×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
13693×
            let body = match (&body, &body_file) {
13703×
                (None, None) => None,
13710×
                _ => Some(body_of(body, body_file)?),
1372
            };
13733×
            let labels = if no_labels {
13741×
                Some(Vec::new())
13752×
            } else if label.is_empty() {
13761×
                None
1377
            } else {
13781×
                Some(label)
1379
            };
13803×
            let assignees = if no_assignees {
13811×
                Some(Vec::new())
13822×
            } else if assignee.is_empty() {
13831×
                None
1384
            } else {
13851×
                Some(assignee)
1386
            };
13873×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
13881×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
13892×
            }
13902×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
13912×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
13922×
            if json {
13931×
                println!("{}", serde_json::to_string(&i)?);
13941×
            } else {
13951×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13961×
            }
1397
        }
13980×
        IssueCmd::Label(change) => {
13990×
            let path = format!("{base}/issues/{}", change.number);
14000×
            let now: Issue = c.get(&path)?;
14010×
            let labels = change.apply(&now.labels)?;
14020×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
14030×
            let i: Issue = c.send("PATCH", &path, &edit)?;
14040×
            if json {
14050×
                println!("{}", serde_json::to_string(&i)?);
14060×
            } else {
14070×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
14080×
            }
1409
        }
14103×
        IssueCmd::Comment { number, body, body_file } => {
14113×
            let body = body_of(body, body_file)?;
14123×
            if body.trim().is_empty() {
14131×
                bail!("give the comment with --body or --body-file");
14142×
            }
14152×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
14162×
            println!("{} commented on #{number}", ui::ok("✔"));
1417
        }
1418
    }
141910×
    Ok(0)
142015×
}
1421
14221×
fn source_name(s: &hub_api::ProposalSource) -> String {
14231×
    match s {
14241×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
14250×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
14260×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1427
    }
14281×
}
1429
14301×
fn proposal_line(p: &Proposal) -> String {
14311×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
14321×
    let glyph = match state.as_str() {
14331×
        "open" => ui::ok("●"),
14340×
        "draft" => ui::dim("◌"),
14350×
        "landed" => ui::strong("✔"),
14360×
        _ => ui::dim("○"),
1437
    };
14381×
    format!(
1439
        "{glyph} {} {} {}{}",
14401×
        ui::dim(&format!("#{}", p.number)),
1441
        p.title,
14421×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
14431×
        ui::dim(&format!(" · {} · {state}", p.author))
1444
    )
14451×
}
1446
14474×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
14484×
    let base = t.repo_path()?;
14494×
    match cmd {
14500×
        ProposalCmd::List { state, limit } => {
14510×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
14520×
            if json {
14530×
                println!("{}", c.get_text(&path)?);
14540×
                return Ok(0);
14550×
            }
14560×
            let list: Vec<Proposal> = c.get(&path)?;
14570×
            if list.is_empty() {
14580×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
14590×
            }
14600×
            for p in &list {
14610×
                println!("{}", proposal_line(p));
14620×
            }
1463
        }
14641×
        ProposalCmd::View { number } => {
14651×
            let path = format!("{base}/proposals/{number}");
14661×
            if json {
14670×
                println!("{}", c.get_text(&path)?);
14680×
                return Ok(0);
14691×
            }
14701×
            let p: Proposal = c.get(&path)?;
14711×
            println!("{}", proposal_line(&p));
14721×
            if !p.body.trim().is_empty() {
14730×
                println!("\n{}\n", p.body.trim_end());
14741×
            }
14751×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
14761×
            for ch in &p.changes {
14771×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
14781×
            }
14791×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
14801×
            if p.landable {
14811×
                println!("{} can land", ui::ok("✔"));
14821×
            } else {
14830×
                for b in &p.blockers {
14840×
                    println!("{} {b}", ui::bad("✘"));
14850×
                }
1486
            }
14871×
            if p.conflicted {
14880×
                println!("{} landing it would leave conflicts", ui::bad("!"));
14891×
            }
14901×
            println!("{}", ui::dim(&p.url));
1491
        }
14921×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
14931×
            let target = match into {
14940×
                Some(i) => i,
14951×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1496
            };
14971×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
14981×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
14991×
            if json {
15000×
                println!("{}", serde_json::to_string(&p)?);
15011×
            } else {
15021×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15031×
            }
1504
        }
15050×
        ProposalCmd::Edit { number, title, body, body_file } => {
15060×
            let body = match (&body, &body_file) {
15070×
                (None, None) => None,
15080×
                _ => Some(body_of(body, body_file)?),
1509
            };
15100×
            if title.is_none() && body.is_none() {
15110×
                bail!("say what to change: --title, --body or --body-file");
15120×
            }
15130×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
15140×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15150×
            if json {
15160×
                println!("{}", serde_json::to_string(&p)?);
15170×
            } else {
15180×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15190×
            }
1520
        }
15210×
        ProposalCmd::Label(change) => {
15220×
            let path = format!("{base}/proposals/{}", change.number);
15230×
            let now: Proposal = c.get(&path)?;
15240×
            let labels = change.apply(&now.labels)?;
15250×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
15260×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
15270×
            if json {
15280×
                println!("{}", serde_json::to_string(&p)?);
15290×
            } else {
15300×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
15310×
            }
1532
        }
15330×
        ProposalCmd::Comment { number, body, body_file } => {
15340×
            let body = body_of(body, body_file)?;
15350×
            if body.trim().is_empty() {
15360×
                bail!("give the comment with --body or --body-file");
15370×
            }
15380×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15390×
            println!("{} commented on #{number}", ui::ok("✔"));
1540
        }
15410×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
15420×
            let path = format!("{base}/proposals/{number}/auto-land");
15430×
            let p: Proposal =
15440×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
15450×
            if json {
15460×
                println!("{}", serde_json::to_string(&p)?);
15470×
            } else if p.landed.is_some() {
15480×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
15490×
            } else if p.auto_land.is_some() {
15500×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
15510×
            } else {
15520×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
15530×
            }
1554
        }
15552×
        ProposalCmd::Land { number, over_checks, .. } => {
15562×
            let body = match &over_checks {
15570×
                Some(r) => serde_json::json!({ "over_checks": r }),
15582×
                None => serde_json::json!({}),
1559
            };
15602×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
15611×
            if json {
15620×
                println!("{}", serde_json::to_string(&p)?);
15631×
            } else {
15641×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
15651×
            }
1566
        }
15670×
        ProposalCmd::Close { number, message } => {
15680×
            if let Some(body) = message {
15690×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15700×
            }
15710×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
15720×
            if json {
15730×
                println!("{}", serde_json::to_string(&p)?);
15740×
            } else {
15750×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
15760×
            }
1577
        }
15780×
        ProposalCmd::Reopen { number } => {
15790×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
15800×
            if json {
15810×
                println!("{}", serde_json::to_string(&p)?);
15820×
            } else {
15830×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
15840×
            }
1585
        }
15860×
        ProposalCmd::Ready { number, undo } => {
15870×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
15880×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15890×
            if json {
15900×
                println!("{}", serde_json::to_string(&p)?);
15910×
            } else if undo {
15920×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
15930×
            } else {
15940×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
15950×
            }
1596
        }
15970×
        ProposalCmd::Checks { number } => {
15980×
            let path = format!("{base}/proposals/{number}/checks");
15990×
            if json {
16000×
                println!("{}", c.get_text(&path)?);
16010×
                return Ok(0);
16020×
            }
16030×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
16040×
            if checks.is_empty() {
16050×
                println!("{}", ui::dim("No checks yet."));
16060×
            }
16070×
            for ch in checks {
16080×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
16090×
            }
1610
        }
1611
    }
16123×
    Ok(0)
16134×
}
1614
16151×
fn run_line(r: &FlowRun) -> String {
16161×
    let what =
16171×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
16181×
    format!(
1619
        "{} {} {} {}",
16201×
        ui::status(&r.status),
16211×
        ui::dim(&format!("#{}", r.number)),
1622
        what,
16231×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1624
    )
16251×
}
1626
16271×
fn print_run(r: &FlowRun) {
16281×
    println!("{}", run_line(r));
16291×
    for j in &r.jobs {
16301×
        let dur = match (j.started_ms, j.finished_ms) {
16310×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
16321×
            _ => String::new(),
1633
        };
16341×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
16351×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1636
        // Why a queued job no runner can take waits (oxygenhub#28), and
1637
        // why a job ran where it did (oxygenflow#42).
16381×
        if j.status == "queued" && !j.waiting.is_empty() {
16390×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
16401×
        } else if !j.placed.is_empty() {
16410×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
16421×
        }
1643
    }
16441×
    if !r.error.is_empty() {
16450×
        println!("{}", ui::bad(&r.error));
16461×
    }
16471×
    println!("{}", ui::dim(&r.url));
16481×
}
1649
16500×
fn live(status: &str) -> bool {
16510×
    matches!(status, "queued" | "running")
16520×
}
1653
1654
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
16550×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
16560×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
16570×
    if json {
16580×
        println!("{done}");
16590×
    } else {
16600×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
16610×
    }
16620×
    Ok(())
16630×
}
1664
16650×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
16660×
    let path = format!("{base}/flow/runs/{number}");
16670×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1668
    loop {
16690×
        let r: FlowRun = c.get(&path)?;
16700×
        if !json {
16710×
            for j in &r.jobs {
16720×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
16730×
                if seen.get(&j.name) != Some(&shown) {
16740×
                    println!("{} {}", ui::status(&j.status), j.name);
16750×
                    if j.status == "queued" && !j.waiting.is_empty() {
16760×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
16770×
                    }
16780×
                    seen.insert(j.name.clone(), shown);
16790×
                }
1680
            }
16810×
        }
16820×
        if !live(&r.status) {
16830×
            if json {
16840×
                println!("{}", serde_json::to_string(&r)?);
16850×
            } else {
16860×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
16870×
            }
16880×
            return Ok(if r.status == "passed" { 0 } else { 1 });
16890×
        }
16900×
        std::thread::sleep(Duration::from_secs(3));
1691
    }
16920×
}
1693
16943×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
16953×
    let base = t.repo_path()?;
16960×
    match cmd {
16971×
        RunCmd::List { limit } => {
16981×
            let path = format!("{base}/flow/runs?limit={limit}");
16991×
            if json {
17001×
                println!("{}", c.get_text(&path)?);
17011×
                return Ok(0);
17020×
            }
17030×
            let runs: Vec<FlowRun> = c.get(&path)?;
17040×
            if runs.is_empty() {
17050×
                println!("{}", ui::dim("No runs yet."));
17060×
            }
17070×
            for r in &runs {
17080×
                println!("{}", run_line(r));
17090×
            }
1710
        }
17111×
        RunCmd::View { number } => {
17121×
            let path = format!("{base}/flow/runs/{number}");
17131×
            if json {
17140×
                println!("{}", c.get_text(&path)?);
17150×
                return Ok(0);
17161×
            }
17171×
            print_run(&c.get(&path)?);
1718
        }
17191×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
17201×
            let mut body = match (bookmark, change) {
17210×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
17220×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
17231×
                (None, None) => serde_json::json!({}),
1724
            };
17251×
            if !jobs.is_empty() {
17260×
                body["jobs"] = serde_json::json!(jobs);
17271×
            }
17281×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
17291×
            let n = started["number"].as_i64().context("the hub named no run")?;
17301×
            if !json || !follow {
17311×
                if json {
17320×
                    println!("{started}");
17331×
                } else {
17341×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
17351×
                }
17360×
            }
17371×
            if follow {
17380×
                return watch(c, &base, n, json);
17391×
            }
1740
        }
17410×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
17420×
        RunCmd::Log { number, job } => {
17430×
            let mut after = 0;
1744
            loop {
17450×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
17460×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
17470×
                if lines.is_empty() {
17480×
                    break;
17490×
                }
17500×
                for l in &lines {
17510×
                    if json {
17520×
                        println!("{}", serde_json::to_string(l)?);
17530×
                    } else if l.stream == "flow" {
17540×
                        println!("{}", ui::dim(&l.text));
17550×
                    } else {
17560×
                        println!("{}", l.text);
17570×
                    }
1758
                }
17590×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1760
            }
1761
        }
17620×
        RunCmd::Rerun { number, job: Some(job) } => {
17630×
            let queued: serde_json::Value =
17640×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
17650×
            if json {
17660×
                println!("{queued}");
17670×
            } else {
17680×
                let n = queued["queued"].as_i64().unwrap_or(1);
17690×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
17700×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1771
            }
1772
        }
17730×
        RunCmd::Rerun { number, job: None } => {
17740×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
17750×
            if json {
17760×
                println!("{started}");
17770×
            } else {
17780×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
17790×
            }
1780
        }
17810×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
17820×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
17830×
        RunCmd::Cancel { number } => {
17840×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
17850×
            if json {
17860×
                println!("{done}");
17870×
            } else {
17880×
                println!("{} cancelled run #{number}", ui::ok("✔"));
17890×
            }
1790
        }
1791
    }
17922×
    Ok(0)
17933×
}
1794
17950×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
17960×
    let base = t.repo_path()?;
17970×
    match cmd {
1798
        LabelCmd::List => {
17990×
            let path = format!("{base}/labels");
18000×
            if json {
18010×
                println!("{}", c.get_text(&path)?);
18020×
                return Ok(0);
18030×
            }
18040×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
18050×
            if labels.is_empty() {
18060×
                println!("{}", ui::dim("No labels."));
18070×
            }
18080×
            for l in labels {
18090×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
18100×
            }
1811
        }
18120×
        LabelCmd::Create { name, colour, description } => {
18130×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
18140×
            if json {
18150×
                println!("{}", serde_json::to_string(&l)?);
18160×
            } else {
18170×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
18180×
            }
1819
        }
18200×
        LabelCmd::Delete { name } => {
18210×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
18220×
            println!("{} deleted label {name}", ui::ok("✔"));
1823
        }
1824
    }
18250×
    Ok(0)
18260×
}
1827
18280×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
18290×
    let base = match (&org, site) {
18300×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
18310×
        (None, true) => "/admin/assistants".to_string(),
18320×
        (None, false) => format!("{}/assistants", t.repo_path()?),
1833
    };
18340×
    match cmd {
1835
        AssistantCmd::List => {
18360×
            if json {
18370×
                println!("{}", c.get_text(&base)?);
18380×
                return Ok(0);
18390×
            }
18400×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
18410×
            if list.is_empty() {
18420×
                println!("{}", ui::dim("No assistants."));
18430×
            }
18440×
            for a in list {
18450×
                let state = if a.enabled && !a.off_above {
18460×
                    ui::ok("on")
18470×
                } else if a.off_above {
18480×
                    ui::dim("off above")
1849
                } else {
18500×
                    ui::dim("off")
1851
                };
18520×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
18530×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1854
            }
1855
        }
18560×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
18570×
            let token = match token_env {
18580×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
18590×
                None => String::new(),
1860
            };
18610×
            let body =
18620×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
18630×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
18640×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1865
        }
18660×
        AssistantCmd::Remove { name } => {
18670×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
18680×
            println!("{} removed {name}", ui::ok("✔"));
1869
        }
18700×
        AssistantCmd::Prompt { set } => {
18710×
            let p: hub_api::AssistantPrompt = match set {
18720×
                Some(path) => {
18730×
                    let text = if path.as_os_str() == "-" {
18740×
                        let mut s = String::new();
18750×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
18760×
                        s
1877
                    } else {
18780×
                        std::fs::read_to_string(&path)?
1879
                    };
18800×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1881
                }
18820×
                None => c.get(&format!("{base}/prompt"))?,
1883
            };
18840×
            if json {
18850×
                println!("{}", serde_json::to_string(&p)?);
18860×
                return Ok(0);
18870×
            }
18880×
            for (from, text) in &p.inherited {
18890×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
18900×
            }
18910×
            if p.prompt.is_empty() {
18920×
                println!("{}", ui::dim("No prompt of its own."));
18930×
            } else {
18940×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
18950×
            }
1896
        }
1897
    }
18980×
    Ok(0)
18990×
}
1900
19012×
fn project_line(p: &hub_api::Project) -> String {
19022×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
19032×
    let private = if p.public { "" } else { " · private" };
19042×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
19052×
}
1906
190710×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
190810×
    let owner = match owner {
19090×
        Some(o) => o,
191010×
        None => t.repo()?.0.to_string(),
1911
    };
191210×
    let base = format!("/projects/{}", enc(&owner));
191310×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
19141×
        let p: hub_api::Project =
19151×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
19161×
        if json {
19170×
            println!("{}", serde_json::to_string(&p)?);
19181×
        } else {
19191×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
19201×
        }
19211×
        Ok(())
19221×
    };
19234×
    match cmd {
1924
        ProjectCmd::List => {
19251×
            if json {
19260×
                println!("{}", c.get_text(&base)?);
19270×
                return Ok(0);
19281×
            }
19291×
            let list: Vec<hub_api::Project> = c.get(&base)?;
19301×
            if list.is_empty() {
19310×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
19321×
            }
19331×
            for p in &list {
19341×
                println!("{}", project_line(p));
19351×
            }
1936
        }
19373×
        ProjectCmd::View { number, archived } => {
19383×
            let path = format!("{base}/{number}");
19393×
            let cards = format!("{path}/cards?archived=true");
19403×
            if json {
19412×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
19422×
                return Ok(0);
19431×
            }
19441×
            let mut b: hub_api::Board = c.get(&path)?;
19451×
            if archived {
19460×
                b.columns = c.get(&cards)?;
19471×
            }
19481×
            println!("{}", project_line(&b.project));
19491×
            if !b.project.description.is_empty() {
19501×
                println!("{}", b.project.description);
19511×
            }
19523×
            for col in &b.columns {
19533×
                println!();
19543×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
19553×
                if col.cards.is_empty() {
19561×
                    println!("  {}", ui::dim("(empty)"));
19572×
                }
19583×
                for card in &col.cards {
19592×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
19602×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
19612×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
19622×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
19632×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
19642×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
1965
                }
1966
            }
19671×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1968
        }
19691×
        ProjectCmd::Create { title, description, private } => {
19701×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
19711×
            if json {
19720×
                println!("{}", serde_json::to_string(&p)?);
19731×
            } else {
19741×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
19751×
            }
1976
        }
19771×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
19780×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
19790×
        ProjectCmd::Transfer { number, to } => {
19800×
            let p: hub_api::Project =
19810×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
19820×
            if json {
19830×
                println!("{}", serde_json::to_string(&p)?);
19840×
            } else {
19850×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
19860×
            }
1987
        }
19882×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1989
            // The hub names a card's issue as `repo#N` among the owner's
1990
            // repositories.
19912×
            let reference = match reference {
19921×
                None => String::new(),
19931×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
19940×
                    Some((o, rest)) if o == owner => rest.to_string(),
19950×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
19960×
                    None => r,
1997
                },
19981×
                Some(r) => {
19991×
                    let n = r.trim_start_matches('#');
20001×
                    if n.parse::<i64>().is_err() {
20010×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
20021×
                    }
20031×
                    format!("{}#{n}", t.repo()?.1)
2004
                }
2005
            };
20062×
            let note = note.unwrap_or_default();
20072×
            if reference.is_empty() && note.is_empty() {
20080×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
20092×
            }
20101×
            let card: hub_api::ProjectCard =
20112×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
20121×
            if json {
20130×
                println!("{}", serde_json::to_string(&card)?);
2014
            } else {
20151×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2016
            }
2017
        }
20181×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
20191×
            (Some(card), None) => {
20201×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
20211×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2022
            }
20230×
            (None, Some(from)) => {
20240×
                let r: hub_api::CardsMoved = c.send(
20250×
                    "POST",
20260×
                    &format!("{base}/{number}/cards/move"),
20270×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
20280×
                )?;
20290×
                if json {
20300×
                    println!("{}", serde_json::to_string(&r)?);
20310×
                    return Ok(0);
20320×
                }
20330×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
20340×
                for m in &r.moved {
20350×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2036
                }
20370×
                let verb = if dry_run { "would move" } else { "moved" };
20380×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2039
            }
20400×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2041
        },
20420×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
20430×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
20440×
                None => None,
20450×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2046
            };
20470×
            let r: hub_api::CardsArchived = c.send(
20480×
                "POST",
20490×
                &format!("{base}/{number}/cards/archive"),
20500×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
20510×
            )?;
20520×
            if json {
20530×
                println!("{}", serde_json::to_string(&r)?);
20540×
                return Ok(0);
20550×
            }
20560×
            let verb = if dry_run { "would archive" } else { "archived" };
20570×
            for a in &r.archived {
20580×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
20590×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2060
            }
20610×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2062
        }
20630×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
20640×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
20650×
            println!("{} card {card} restored", ui::ok("✔"));
2066
        }
20671×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
20681×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
20691×
            println!("{} card {card} removed", ui::ok("✔"));
2070
        }
2071
    }
20727×
    Ok(0)
207310×
}
2074
20750×
fn milestone_line(m: &hub_api::Milestone) -> String {
20760×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
20770×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
20780×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
20790×
}
2080
20810×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
20820×
    let base = t.repo_path()?;
20830×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
20840×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
20850×
        if json {
20860×
            println!("{}", serde_json::to_string(&m)?);
20870×
        } else {
20880×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
20890×
        }
20900×
        Ok(())
20910×
    };
20920×
    match cmd {
2093
        MilestoneCmd::List => {
20940×
            let path = format!("{base}/milestones");
20950×
            if json {
20960×
                println!("{}", c.get_text(&path)?);
20970×
                return Ok(0);
20980×
            }
20990×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
21000×
            if list.is_empty() {
21010×
                println!("{}", ui::dim("No milestones."));
21020×
            }
21030×
            for m in &list {
21040×
                println!("{}", milestone_line(m));
21050×
            }
2106
        }
21070×
        MilestoneCmd::Create { title, description, due } => {
21080×
            let m: hub_api::Milestone =
21090×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
21100×
            if json {
21110×
                println!("{}", serde_json::to_string(&m)?);
21120×
            } else {
21130×
                println!("{} milestone {}", ui::ok("✔"), m.title);
21140×
            }
2115
        }
21160×
        MilestoneCmd::Edit { title, rename, description, due } => {
21170×
            if rename.is_none() && description.is_none() && due.is_none() {
21180×
                bail!("say what to change: --rename, --description or --due");
21190×
            }
21200×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2121
        }
21220×
        MilestoneCmd::Close { title } => {
21230×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2124
        }
21250×
        MilestoneCmd::Reopen { title } => {
21260×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2127
        }
2128
    }
21290×
    Ok(0)
21300×
}
2131
21320×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
21330×
    let base = t.repo_path()?;
21340×
    match cmd {
2135
        TagCmd::List => {
21360×
            let path = format!("{base}/tags");
21370×
            if json {
21380×
                println!("{}", c.get_text(&path)?);
21390×
                return Ok(0);
21400×
            }
21410×
            let tags: Vec<Tag> = c.get(&path)?;
21420×
            if tags.is_empty() {
21430×
                println!("{}", ui::dim("no tags"));
21440×
            }
21450×
            for t in tags {
21460×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
21470×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
21480×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2149
            }
2150
        }
21510×
        TagCmd::Create { name, target, message } => {
21520×
            let new = hub_api::NewTag { name, target, message };
21530×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
21540×
            if json {
21550×
                println!("{}", serde_json::to_string(&made)?);
21560×
            } else {
21570×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
21580×
            }
2159
        }
21600×
        TagCmd::Delete { name, reason } => {
21610×
            let reason = reason.unwrap_or_default();
21620×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
21630×
            if json {
21640×
                println!("{}", serde_json::json!({ "withdrawn": name }));
21650×
            } else {
21660×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
21670×
            }
2168
        }
2169
    }
21700×
    Ok(0)
21710×
}
2172
21734×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
21744×
    let base = t.repo_path()?;
21754×
    match cmd {
2176
        ReleaseCmd::List => {
21771×
            let path = format!("{base}/releases");
21781×
            if json {
21791×
                println!("{}", c.get_text(&path)?);
21801×
                return Ok(0);
21810×
            }
21820×
            let list: Vec<Release> = c.get(&path)?;
21830×
            if list.is_empty() {
21840×
                println!("{}", ui::dim("No releases."));
21850×
            }
21860×
            for r in &list {
21870×
                println!(
2188
                    "{} {} {}{}",
21890×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
21900×
                    ui::strong(&r.tag),
2191
                    r.title,
21920×
                    ui::dim(&format!(
2193
                        " · {} asset{} · {}",
21940×
                        r.assets.len(),
21950×
                        if r.assets.len() == 1 { "" } else { "s" },
21960×
                        ui::ago(r.created_ms)
2197
                    ))
2198
                );
2199
            }
2200
        }
22011×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
22021×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
22031×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
22041×
            if json {
22050×
                println!("{}", serde_json::to_string(&r)?);
22061×
            } else {
22071×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22081×
            }
2209
        }
22100×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
22110×
            let notes = match notes.as_deref() {
22120×
                Some("-") => Some(body_of(None, Some("-".into()))?),
22130×
                _ => notes,
2214
            };
22150×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
22160×
                bail!("say what to change: --title, --notes or --prerelease");
22170×
            }
22180×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
22190×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
22200×
            if json {
22210×
                println!("{}", serde_json::to_string(&r)?);
22220×
            } else {
22230×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22240×
            }
2225
        }
22261×
        ReleaseCmd::Upload { tag, files } => {
22271×
            if files.is_empty() {
22280×
                bail!("name the files to attach");
22291×
            }
22301×
            for f in files {
22311×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
22321×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
22331×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
22341×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2235
            }
2236
        }
22371×
        ReleaseCmd::Trust { tag } => {
22381×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
22391×
            if json {
22400×
                println!("{}", c.get_text(&path)?);
22410×
                return Ok(0);
22421×
            }
22431×
            let r: serde_json::Value = c.get(&path)?;
22441×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
22451×
            let mut worst = 0;
22464×
            for ch in r["audit"].as_array().into_iter().flatten() {
22474×
                let v = ch["verdict"].as_str().unwrap_or("");
22484×
                worst = worst.max(match v {
22494×
                    "fail" => 2,
22504×
                    "warn" => 1,
22513×
                    _ => 0,
2252
                });
22534×
                let g = match v {
22544×
                    "pass" => ui::ok("✔"),
22551×
                    "warn" => ui::warn("!"),
22560×
                    _ => ui::bad("✘"),
2257
                };
22584×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2259
            }
22601×
            return Ok(if worst == 2 { 1 } else { 0 });
2261
        }
2262
    }
22632×
    Ok(0)
22644×
}
2265
2266
#[cfg(test)]
2267
mod tests {
2268
2269
    #[test]
22701×
    fn runner_update_scopes_resolve_by_name_or_id() {
22711×
        let all = hub_api::RunnerUpdates {
22721×
            repo: String::new(),
22731×
            settings: vec![],
22741×
            groups: vec![hub_api::RunnerGroup {
22751×
                id: 4,
22761×
                owner: "acme".into(),
22771×
                name: "canary".into(),
22781×
                percent: None,
22791×
                members: vec![],
22801×
                wave: None,
22811×
            }],
22821×
            runners: vec![],
22831×
            holds: vec![],
22841×
        };
22851×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
22861×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
22873×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
22883×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2289
        }
22901×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
22911×
        assert!(update_scope("everyone", &all).is_err());
22921×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
22931×
        assert!(switch(Some("yes")).is_err());
22941×
    }
2295
    use super::*;
2296
2297
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2298
    /// help says, and a drop is named by its id or its address.
2299
    #[test]
23001×
    fn drop_commands_parse() {
23011×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
23021×
        match cli.cmd {
23031×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
23041×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
23051×
                assert!(secret);
23061×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2307
            }
23080×
            _ => panic!("not drop create"),
2309
        }
23101×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
23111×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
23121×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
23131×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
23141×
                assert!(channel.is_none() && dry_run.is_none());
2315
            }
23160×
            _ => panic!("not runner-updates set"),
2317
        }
23181×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
23191×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
23201×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
23210×
            _ => panic!("not drop list"),
2322
        }
23231×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
23241×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
23251×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2326
            }
23270×
            _ => panic!("not drop view"),
2328
        }
23291×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
23301×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
23311×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
23321×
        assert!(drop_id("andy/notes").is_err());
23331×
    }
2334
}