OXYGENHUB

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

551 of 1356 lines run, 35 of 192 functions · run #515 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 what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
9610×
                println!(
962
                    "  group {} ({what}): {}",
9630×
                    ui::strong(&g.name),
9640×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
965
                );
966
            }
9670×
            for r in &all.runners {
9680×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
9690×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
970
            }
971
        }
9720×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
9730×
            let (scope, key) = update_scope(&scope, &all)?;
9740×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
9750×
                scope: scope.clone(),
9760×
                key: key.clone(),
9770×
                ..Default::default()
9780×
            });
9790×
            if let Some(u) = switch(updates.as_deref())? {
9800×
                s.updates = u;
9810×
            }
9820×
            if let Some(d) = switch(dry_run.as_deref())? {
9830×
                s.dry_run = d;
9840×
            }
9850×
            if let Some(ch) = channel {
9860×
                s.channel = Some(ch).filter(|c| c != "inherit");
9870×
            }
9880×
            if let Some(w) = window {
9890×
                s.window = Some(w).filter(|w| w != "inherit");
9900×
            }
9910×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
9920×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
993
        }
9940×
        RunnerUpdatesCmd::Lift { version } => {
9950×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
9960×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
997
        }
998
    }
9990×
    Ok(0)
10000×
}
1001
1002
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
10037×
fn drop_id(s: &str) -> Result<String> {
10047×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1005144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
10061×
        bail!("{s:?} is not a drop's id or address");
10076×
    }
10086×
    Ok(id.to_ascii_lowercase())
10097×
}
1010
10112×
fn drop_line(d: &hub_api::Drop) -> String {
10122×
    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() };
10134×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
10142×
    format!(
1015
        "{} {} {}{}",
10162×
        ui::dim(&d.id),
10172×
        ui::strong(&title),
10182×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
10192×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1020
    )
10212×
}
1022
10237×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
10247×
    match cmd {
10251×
        DropCmd::Create { files, secret, description, title } => {
10261×
            let mut out = Vec::with_capacity(files.len());
10272×
            for f in &files {
10282×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
10292×
                let content =
10302×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
10312×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1032
            }
10331×
            let new =
10341×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
10351×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
10361×
            if json {
10371×
                println!("{}", serde_json::to_string(&d)?);
1038
            } else {
10390×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
10400×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1041
            }
1042
        }
10432×
        DropCmd::List { user } => {
10442×
            let path = match &user {
10451×
                Some(u) => format!("/users/{}/drops", enc(u)),
10461×
                None => "/drops".to_string(),
1047
            };
10482×
            if json {
10491×
                println!("{}", c.get_text(&path)?);
10501×
                return Ok(0);
10511×
            }
10521×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
10531×
            if list.is_empty() {
10540×
                println!("{}", ui::dim("No drops."));
10551×
            }
10561×
            for d in &list {
10571×
                println!("{}", drop_line(d));
10581×
            }
1059
        }
10603×
        DropCmd::View { id, file } => {
10613×
            let path = format!("/drops/{}", drop_id(&id)?);
10623×
            if json && file.is_none() {
10630×
                println!("{}", c.get_text(&path)?);
10640×
                return Ok(0);
10653×
            }
10663×
            let d: hub_api::Drop = c.get(&path)?;
10672×
            if let Some(name) = file {
10682×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
10691×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
10701×
                print!("{content}");
10711×
                return Ok(0);
10721×
            }
10731×
            println!("{}", drop_line(&d));
10741×
            if !d.description.is_empty() {
10751×
                println!("{}", d.description);
10761×
            }
10771×
            println!("{}", ui::kv("url", &d.url));
10781×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
10792×
            for f in &d.files {
10802×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
10812×
                match &f.content {
10822×
                    Some(text) => {
10832×
                        print!("{text}");
10842×
                        if !text.ends_with('\n') && !text.is_empty() {
10850×
                            println!();
10862×
                        }
1087
                    }
10880×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1089
                }
1090
            }
1091
        }
10921×
        DropCmd::Delete { id } => {
10931×
            let id = drop_id(&id)?;
10941×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
10951×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1096
        }
1097
    }
10984×
    Ok(0)
10997×
}
1100
1101
/// `30d`, `12h`, `90m` in milliseconds.
11020×
fn duration_ms(s: &str) -> Result<i64> {
11030×
    let s = s.trim();
11040×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
11050×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
11060×
    let per = match unit {
11070×
        "d" => 86_400_000,
11080×
        "h" => 3_600_000,
11090×
        "m" => 60_000,
11100×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1111
    };
11120×
    if n <= 0 {
11130×
        bail!("a grant must last some time");
11140×
    }
11150×
    Ok(n * per)
11160×
}
1117
11180×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1119
    use oxy_core::cert::{Grant, SignedGrant};
1120
    use oxy_core::identity::{Identity, Scope};
11210×
    match cmd {
11220×
        AgentCmd::Grant { name, scope, lasts } => {
11230×
            let home = oxy_core::repo::default_home();
11240×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
11250×
                format!(
1126
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
11270×
                    home.display()
1128
                )
11290×
            })?;
11300×
            let me: serde_json::Value = c.get("/user")?;
11310×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
11320×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
11330×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
11340×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11350×
            let grant = Grant {
11360×
                grantor: me_id.hash(),
11370×
                subject: format!("agent:{name}@{username}"),
11380×
                issuer: hub.hash(),
11390×
                scope,
11400×
                not_before: (now - 60_000) as u64,
11410×
                expires: (now + duration_ms(&lasts)?) as u64,
1142
            };
11430×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
11440×
            let r: serde_json::Value =
11450×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
11460×
            if json {
11470×
                println!("{r}");
11480×
                return Ok(0);
11490×
            }
11500×
            println!(
1151
                "{} {} to act for you as {} ({}), until {}",
11520×
                ui::ok("✔ granted"),
11530×
                ui::strong(&name),
11540×
                r["subject"].as_str().unwrap_or(""),
11550×
                r["scope"].as_str().unwrap_or(""),
11560×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1157
            );
11580×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
11590×
            println!(
1160
                "  {}",
11610×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1162
            );
11630×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
11640×
            Ok(0)
1165
        }
1166
        AgentCmd::List => {
11670×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
11680×
            if json {
11690×
                println!("{}", serde_json::to_string(&grants)?);
11700×
                return Ok(0);
11710×
            }
11720×
            if grants.is_empty() {
11730×
                println!("{}", ui::dim("no agent grants"));
11740×
            }
11750×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11760×
            for g in grants {
11770×
                let state = if g["revoked_ms"].is_i64() {
11780×
                    ui::bad("revoked")
11790×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
11800×
                    ui::dim("ended")
1181
                } else {
11820×
                    ui::ok("live")
1183
                };
11840×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
11850×
                println!(
1186
                    "#{:<4} {:<8} {} · {} · until {} · {}",
11870×
                    g["id"],
1188
                    state,
11890×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
11900×
                    g["scope"].as_str().unwrap_or(""),
11910×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
11920×
                    ui::dim(&used)
1193
                );
1194
            }
11950×
            Ok(0)
1196
        }
11970×
        AgentCmd::Revoke { id } => {
11980×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
11990×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
12000×
            Ok(0)
1201
        }
1202
    }
12030×
}
1204
12051×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
12061×
    let hub = url.trim_end_matches('/').to_string();
12071×
    let token = match token.as_deref() {
12081×
        Some("-") => {
12090×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
12100×
            let mut line = String::new();
12110×
            std::io::stdin().read_line(&mut line)?;
12120×
            line.trim().to_string()
1213
        }
12141×
        Some(t) => t.to_string(),
12150×
        None => device_sign_in(&hub, ca.clone())?,
1216
    };
12171×
    if token.is_empty() {
12180×
        bail!("no token given");
12191×
    }
12201×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
12211×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
12221×
    let account = me["username"].as_str().unwrap_or("?");
1223
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
12241×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
12251×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
12261×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
12271×
    cfg.default_hub = Some(hub.clone());
12281×
    cfg.save()?;
12291×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
12301×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
12311×
    Ok(0)
12321×
}
1233
1234
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1235
/// it on the web, and the token arrives here.
12360×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
12370×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
12380×
    let c = Client::new(&t)?;
12390×
    let host = std::fs::read_to_string("/etc/hostname")
12400×
        .ok()
12410×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
12420×
        .map(|h| h.trim().to_string())
12430×
        .filter(|h| !h.is_empty());
12440×
    let client = match host {
12450×
        Some(h) => format!("oh on {h}"),
12460×
        None => "oh".to_string(),
1247
    };
12480×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
12490×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
12500×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
12510×
    if code != 200 {
12520×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
12530×
    }
12540×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
12550×
    let user = v["user_code"].as_str().unwrap_or("?");
12560×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
12570×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
12580×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
12590×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
12600×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1261
    loop {
12620×
        std::thread::sleep(std::time::Duration::from_secs(interval));
12630×
        if std::time::Instant::now() > deadline {
12640×
            bail!("the code expired before it was approved; run oh auth login again");
12650×
        }
12660×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
12670×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
12680×
        if code == 200 {
12690×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
12700×
        }
12710×
        match v["error"].as_str() {
12720×
            Some("authorization_pending") => {}
12730×
            Some("slow_down") => interval += 5,
12740×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
12750×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
12760×
            _ => bail!("signing in: HTTP {code}: {body}"),
1277
        }
1278
    }
12790×
}
1280
12817×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
12827×
    match (body, file) {
12832×
        (Some(b), _) => Ok(b),
12841×
        (None, Some(f)) if f == "-" => {
12850×
            let mut s = String::new();
12860×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
12870×
            Ok(s)
1288
        }
12891×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
12904×
        (None, None) => Ok(String::new()),
1291
    }
12927×
}
1293
12943×
fn issue_line(i: &Issue) -> String {
12953×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
12963×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
12973×
    format!(
1298
        "{glyph} {} {}{}{}",
12993×
        ui::dim(&format!("#{}", i.number)),
1300
        i.title,
13013×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
13023×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1303
    )
13043×
}
1305
130615×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
130715×
    let base = t.repo_path()?;
130815×
    match cmd {
13093×
        IssueCmd::List { state } => {
13103×
            let path = format!("{base}/issues?state={}", enc(&state));
13113×
            if json {
13121×
                println!("{}", c.get_text(&path)?);
13131×
                return Ok(0);
13142×
            }
13152×
            let list: Vec<Issue> = c.get(&path)?;
13162×
            if list.is_empty() {
13171×
                println!("{}", ui::dim(&format!("No {state} issues.")));
13181×
            }
13192×
            for i in &list {
13202×
                println!("{}", issue_line(i));
13212×
            }
1322
        }
13232×
        IssueCmd::View { number } => {
13242×
            let path = format!("{base}/issues/{number}");
13252×
            if json {
13261×
                println!("{}", c.get_text(&path)?);
13271×
                return Ok(0);
13281×
            }
13291×
            let i: Issue = c.get(&path)?;
13301×
            println!("{}", issue_line(&i));
13311×
            if !i.body.trim().is_empty() {
13321×
                println!("\n{}\n", i.body.trim_end());
13331×
            }
13341×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
13352×
            for cm in comments {
13362×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
13372×
            }
13381×
            println!("{}", ui::dim(&i.url));
1339
        }
13403×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
13413×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
13423×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
13432×
            if json {
13440×
                println!("{}", serde_json::to_string(&i)?);
13452×
            } else {
13462×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13472×
            }
13482×
            if let Some(n) = project {
13491×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
13501×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
13511×
                if !json {
13521×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
13531×
                }
13541×
            }
1355
        }
13561×
        IssueCmd::Close { number, reason } => {
13571×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
13581×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1359
        }
13600×
        IssueCmd::Reopen { number } => {
13610×
            let i: Issue =
13620×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
13630×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1364
        }
13653×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
13663×
            let body = match (&body, &body_file) {
13673×
                (None, None) => None,
13680×
                _ => Some(body_of(body, body_file)?),
1369
            };
13703×
            let labels = if no_labels {
13711×
                Some(Vec::new())
13722×
            } else if label.is_empty() {
13731×
                None
1374
            } else {
13751×
                Some(label)
1376
            };
13773×
            let assignees = if no_assignees {
13781×
                Some(Vec::new())
13792×
            } else if assignee.is_empty() {
13801×
                None
1381
            } else {
13821×
                Some(assignee)
1383
            };
13843×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
13851×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
13862×
            }
13872×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
13882×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
13892×
            if json {
13901×
                println!("{}", serde_json::to_string(&i)?);
13911×
            } else {
13921×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13931×
            }
1394
        }
13950×
        IssueCmd::Label(change) => {
13960×
            let path = format!("{base}/issues/{}", change.number);
13970×
            let now: Issue = c.get(&path)?;
13980×
            let labels = change.apply(&now.labels)?;
13990×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
14000×
            let i: Issue = c.send("PATCH", &path, &edit)?;
14010×
            if json {
14020×
                println!("{}", serde_json::to_string(&i)?);
14030×
            } else {
14040×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
14050×
            }
1406
        }
14073×
        IssueCmd::Comment { number, body, body_file } => {
14083×
            let body = body_of(body, body_file)?;
14093×
            if body.trim().is_empty() {
14101×
                bail!("give the comment with --body or --body-file");
14112×
            }
14122×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
14132×
            println!("{} commented on #{number}", ui::ok("✔"));
1414
        }
1415
    }
141610×
    Ok(0)
141715×
}
1418
14191×
fn source_name(s: &hub_api::ProposalSource) -> String {
14201×
    match s {
14211×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
14220×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
14230×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1424
    }
14251×
}
1426
14271×
fn proposal_line(p: &Proposal) -> String {
14281×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
14291×
    let glyph = match state.as_str() {
14301×
        "open" => ui::ok("●"),
14310×
        "draft" => ui::dim("◌"),
14320×
        "landed" => ui::strong("✔"),
14330×
        _ => ui::dim("○"),
1434
    };
14351×
    format!(
1436
        "{glyph} {} {} {}{}",
14371×
        ui::dim(&format!("#{}", p.number)),
1438
        p.title,
14391×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
14401×
        ui::dim(&format!(" · {} · {state}", p.author))
1441
    )
14421×
}
1443
14444×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
14454×
    let base = t.repo_path()?;
14464×
    match cmd {
14470×
        ProposalCmd::List { state, limit } => {
14480×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
14490×
            if json {
14500×
                println!("{}", c.get_text(&path)?);
14510×
                return Ok(0);
14520×
            }
14530×
            let list: Vec<Proposal> = c.get(&path)?;
14540×
            if list.is_empty() {
14550×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
14560×
            }
14570×
            for p in &list {
14580×
                println!("{}", proposal_line(p));
14590×
            }
1460
        }
14611×
        ProposalCmd::View { number } => {
14621×
            let path = format!("{base}/proposals/{number}");
14631×
            if json {
14640×
                println!("{}", c.get_text(&path)?);
14650×
                return Ok(0);
14661×
            }
14671×
            let p: Proposal = c.get(&path)?;
14681×
            println!("{}", proposal_line(&p));
14691×
            if !p.body.trim().is_empty() {
14700×
                println!("\n{}\n", p.body.trim_end());
14711×
            }
14721×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
14731×
            for ch in &p.changes {
14741×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
14751×
            }
14761×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
14771×
            if p.landable {
14781×
                println!("{} can land", ui::ok("✔"));
14791×
            } else {
14800×
                for b in &p.blockers {
14810×
                    println!("{} {b}", ui::bad("✘"));
14820×
                }
1483
            }
14841×
            if p.conflicted {
14850×
                println!("{} landing it would leave conflicts", ui::bad("!"));
14861×
            }
14871×
            println!("{}", ui::dim(&p.url));
1488
        }
14891×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
14901×
            let target = match into {
14910×
                Some(i) => i,
14921×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1493
            };
14941×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
14951×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
14961×
            if json {
14970×
                println!("{}", serde_json::to_string(&p)?);
14981×
            } else {
14991×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15001×
            }
1501
        }
15020×
        ProposalCmd::Edit { number, title, body, body_file } => {
15030×
            let body = match (&body, &body_file) {
15040×
                (None, None) => None,
15050×
                _ => Some(body_of(body, body_file)?),
1506
            };
15070×
            if title.is_none() && body.is_none() {
15080×
                bail!("say what to change: --title, --body or --body-file");
15090×
            }
15100×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
15110×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15120×
            if json {
15130×
                println!("{}", serde_json::to_string(&p)?);
15140×
            } else {
15150×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15160×
            }
1517
        }
15180×
        ProposalCmd::Label(change) => {
15190×
            let path = format!("{base}/proposals/{}", change.number);
15200×
            let now: Proposal = c.get(&path)?;
15210×
            let labels = change.apply(&now.labels)?;
15220×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
15230×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
15240×
            if json {
15250×
                println!("{}", serde_json::to_string(&p)?);
15260×
            } else {
15270×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
15280×
            }
1529
        }
15300×
        ProposalCmd::Comment { number, body, body_file } => {
15310×
            let body = body_of(body, body_file)?;
15320×
            if body.trim().is_empty() {
15330×
                bail!("give the comment with --body or --body-file");
15340×
            }
15350×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15360×
            println!("{} commented on #{number}", ui::ok("✔"));
1537
        }
15380×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
15390×
            let path = format!("{base}/proposals/{number}/auto-land");
15400×
            let p: Proposal =
15410×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
15420×
            if json {
15430×
                println!("{}", serde_json::to_string(&p)?);
15440×
            } else if p.landed.is_some() {
15450×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
15460×
            } else if p.auto_land.is_some() {
15470×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
15480×
            } else {
15490×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
15500×
            }
1551
        }
15522×
        ProposalCmd::Land { number, over_checks, .. } => {
15532×
            let body = match &over_checks {
15540×
                Some(r) => serde_json::json!({ "over_checks": r }),
15552×
                None => serde_json::json!({}),
1556
            };
15572×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
15581×
            if json {
15590×
                println!("{}", serde_json::to_string(&p)?);
15601×
            } else {
15611×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
15621×
            }
1563
        }
15640×
        ProposalCmd::Close { number, message } => {
15650×
            if let Some(body) = message {
15660×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15670×
            }
15680×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
15690×
            if json {
15700×
                println!("{}", serde_json::to_string(&p)?);
15710×
            } else {
15720×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
15730×
            }
1574
        }
15750×
        ProposalCmd::Reopen { number } => {
15760×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
15770×
            if json {
15780×
                println!("{}", serde_json::to_string(&p)?);
15790×
            } else {
15800×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
15810×
            }
1582
        }
15830×
        ProposalCmd::Ready { number, undo } => {
15840×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
15850×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15860×
            if json {
15870×
                println!("{}", serde_json::to_string(&p)?);
15880×
            } else if undo {
15890×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
15900×
            } else {
15910×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
15920×
            }
1593
        }
15940×
        ProposalCmd::Checks { number } => {
15950×
            let path = format!("{base}/proposals/{number}/checks");
15960×
            if json {
15970×
                println!("{}", c.get_text(&path)?);
15980×
                return Ok(0);
15990×
            }
16000×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
16010×
            if checks.is_empty() {
16020×
                println!("{}", ui::dim("No checks yet."));
16030×
            }
16040×
            for ch in checks {
16050×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
16060×
            }
1607
        }
1608
    }
16093×
    Ok(0)
16104×
}
1611
16121×
fn run_line(r: &FlowRun) -> String {
16131×
    let what =
16141×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
16151×
    format!(
1616
        "{} {} {} {}",
16171×
        ui::status(&r.status),
16181×
        ui::dim(&format!("#{}", r.number)),
1619
        what,
16201×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1621
    )
16221×
}
1623
16241×
fn print_run(r: &FlowRun) {
16251×
    println!("{}", run_line(r));
16261×
    for j in &r.jobs {
16271×
        let dur = match (j.started_ms, j.finished_ms) {
16280×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
16291×
            _ => String::new(),
1630
        };
16311×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
16321×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1633
        // Why a queued job no runner can take waits (oxygenhub#28), and
1634
        // why a job ran where it did (oxygenflow#42).
16351×
        if j.status == "queued" && !j.waiting.is_empty() {
16360×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
16371×
        } else if !j.placed.is_empty() {
16380×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
16391×
        }
1640
    }
16411×
    if !r.error.is_empty() {
16420×
        println!("{}", ui::bad(&r.error));
16431×
    }
16441×
    println!("{}", ui::dim(&r.url));
16451×
}
1646
16470×
fn live(status: &str) -> bool {
16480×
    matches!(status, "queued" | "running")
16490×
}
1650
1651
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
16520×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
16530×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
16540×
    if json {
16550×
        println!("{done}");
16560×
    } else {
16570×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
16580×
    }
16590×
    Ok(())
16600×
}
1661
16620×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
16630×
    let path = format!("{base}/flow/runs/{number}");
16640×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1665
    loop {
16660×
        let r: FlowRun = c.get(&path)?;
16670×
        if !json {
16680×
            for j in &r.jobs {
16690×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
16700×
                if seen.get(&j.name) != Some(&shown) {
16710×
                    println!("{} {}", ui::status(&j.status), j.name);
16720×
                    if j.status == "queued" && !j.waiting.is_empty() {
16730×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
16740×
                    }
16750×
                    seen.insert(j.name.clone(), shown);
16760×
                }
1677
            }
16780×
        }
16790×
        if !live(&r.status) {
16800×
            if json {
16810×
                println!("{}", serde_json::to_string(&r)?);
16820×
            } else {
16830×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
16840×
            }
16850×
            return Ok(if r.status == "passed" { 0 } else { 1 });
16860×
        }
16870×
        std::thread::sleep(Duration::from_secs(3));
1688
    }
16890×
}
1690
16913×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
16923×
    let base = t.repo_path()?;
16930×
    match cmd {
16941×
        RunCmd::List { limit } => {
16951×
            let path = format!("{base}/flow/runs?limit={limit}");
16961×
            if json {
16971×
                println!("{}", c.get_text(&path)?);
16981×
                return Ok(0);
16990×
            }
17000×
            let runs: Vec<FlowRun> = c.get(&path)?;
17010×
            if runs.is_empty() {
17020×
                println!("{}", ui::dim("No runs yet."));
17030×
            }
17040×
            for r in &runs {
17050×
                println!("{}", run_line(r));
17060×
            }
1707
        }
17081×
        RunCmd::View { number } => {
17091×
            let path = format!("{base}/flow/runs/{number}");
17101×
            if json {
17110×
                println!("{}", c.get_text(&path)?);
17120×
                return Ok(0);
17131×
            }
17141×
            print_run(&c.get(&path)?);
1715
        }
17161×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
17171×
            let mut body = match (bookmark, change) {
17180×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
17190×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
17201×
                (None, None) => serde_json::json!({}),
1721
            };
17221×
            if !jobs.is_empty() {
17230×
                body["jobs"] = serde_json::json!(jobs);
17241×
            }
17251×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
17261×
            let n = started["number"].as_i64().context("the hub named no run")?;
17271×
            if !json || !follow {
17281×
                if json {
17290×
                    println!("{started}");
17301×
                } else {
17311×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
17321×
                }
17330×
            }
17341×
            if follow {
17350×
                return watch(c, &base, n, json);
17361×
            }
1737
        }
17380×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
17390×
        RunCmd::Log { number, job } => {
17400×
            let mut after = 0;
1741
            loop {
17420×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
17430×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
17440×
                if lines.is_empty() {
17450×
                    break;
17460×
                }
17470×
                for l in &lines {
17480×
                    if json {
17490×
                        println!("{}", serde_json::to_string(l)?);
17500×
                    } else if l.stream == "flow" {
17510×
                        println!("{}", ui::dim(&l.text));
17520×
                    } else {
17530×
                        println!("{}", l.text);
17540×
                    }
1755
                }
17560×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1757
            }
1758
        }
17590×
        RunCmd::Rerun { number, job: Some(job) } => {
17600×
            let queued: serde_json::Value =
17610×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
17620×
            if json {
17630×
                println!("{queued}");
17640×
            } else {
17650×
                let n = queued["queued"].as_i64().unwrap_or(1);
17660×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
17670×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1768
            }
1769
        }
17700×
        RunCmd::Rerun { number, job: None } => {
17710×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
17720×
            if json {
17730×
                println!("{started}");
17740×
            } else {
17750×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
17760×
            }
1777
        }
17780×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
17790×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
17800×
        RunCmd::Cancel { number } => {
17810×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
17820×
            if json {
17830×
                println!("{done}");
17840×
            } else {
17850×
                println!("{} cancelled run #{number}", ui::ok("✔"));
17860×
            }
1787
        }
1788
    }
17892×
    Ok(0)
17903×
}
1791
17920×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
17930×
    let base = t.repo_path()?;
17940×
    match cmd {
1795
        LabelCmd::List => {
17960×
            let path = format!("{base}/labels");
17970×
            if json {
17980×
                println!("{}", c.get_text(&path)?);
17990×
                return Ok(0);
18000×
            }
18010×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
18020×
            if labels.is_empty() {
18030×
                println!("{}", ui::dim("No labels."));
18040×
            }
18050×
            for l in labels {
18060×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
18070×
            }
1808
        }
18090×
        LabelCmd::Create { name, colour, description } => {
18100×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
18110×
            if json {
18120×
                println!("{}", serde_json::to_string(&l)?);
18130×
            } else {
18140×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
18150×
            }
1816
        }
18170×
        LabelCmd::Delete { name } => {
18180×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
18190×
            println!("{} deleted label {name}", ui::ok("✔"));
1820
        }
1821
    }
18220×
    Ok(0)
18230×
}
1824
18250×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
18260×
    let base = match (&org, site) {
18270×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
18280×
        (None, true) => "/admin/assistants".to_string(),
18290×
        (None, false) => format!("{}/assistants", t.repo_path()?),
1830
    };
18310×
    match cmd {
1832
        AssistantCmd::List => {
18330×
            if json {
18340×
                println!("{}", c.get_text(&base)?);
18350×
                return Ok(0);
18360×
            }
18370×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
18380×
            if list.is_empty() {
18390×
                println!("{}", ui::dim("No assistants."));
18400×
            }
18410×
            for a in list {
18420×
                let state = if a.enabled && !a.off_above {
18430×
                    ui::ok("on")
18440×
                } else if a.off_above {
18450×
                    ui::dim("off above")
1846
                } else {
18470×
                    ui::dim("off")
1848
                };
18490×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
18500×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1851
            }
1852
        }
18530×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
18540×
            let token = match token_env {
18550×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
18560×
                None => String::new(),
1857
            };
18580×
            let body =
18590×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
18600×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
18610×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1862
        }
18630×
        AssistantCmd::Remove { name } => {
18640×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
18650×
            println!("{} removed {name}", ui::ok("✔"));
1866
        }
18670×
        AssistantCmd::Prompt { set } => {
18680×
            let p: hub_api::AssistantPrompt = match set {
18690×
                Some(path) => {
18700×
                    let text = if path.as_os_str() == "-" {
18710×
                        let mut s = String::new();
18720×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
18730×
                        s
1874
                    } else {
18750×
                        std::fs::read_to_string(&path)?
1876
                    };
18770×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1878
                }
18790×
                None => c.get(&format!("{base}/prompt"))?,
1880
            };
18810×
            if json {
18820×
                println!("{}", serde_json::to_string(&p)?);
18830×
                return Ok(0);
18840×
            }
18850×
            for (from, text) in &p.inherited {
18860×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
18870×
            }
18880×
            if p.prompt.is_empty() {
18890×
                println!("{}", ui::dim("No prompt of its own."));
18900×
            } else {
18910×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
18920×
            }
1893
        }
1894
    }
18950×
    Ok(0)
18960×
}
1897
18982×
fn project_line(p: &hub_api::Project) -> String {
18992×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
19002×
    let private = if p.public { "" } else { " · private" };
19012×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
19022×
}
1903
190410×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
190510×
    let owner = match owner {
19060×
        Some(o) => o,
190710×
        None => t.repo()?.0.to_string(),
1908
    };
190910×
    let base = format!("/projects/{}", enc(&owner));
191010×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
19111×
        let p: hub_api::Project =
19121×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
19131×
        if json {
19140×
            println!("{}", serde_json::to_string(&p)?);
19151×
        } else {
19161×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
19171×
        }
19181×
        Ok(())
19191×
    };
19204×
    match cmd {
1921
        ProjectCmd::List => {
19221×
            if json {
19230×
                println!("{}", c.get_text(&base)?);
19240×
                return Ok(0);
19251×
            }
19261×
            let list: Vec<hub_api::Project> = c.get(&base)?;
19271×
            if list.is_empty() {
19280×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
19291×
            }
19301×
            for p in &list {
19311×
                println!("{}", project_line(p));
19321×
            }
1933
        }
19343×
        ProjectCmd::View { number, archived } => {
19353×
            let path = format!("{base}/{number}");
19363×
            let cards = format!("{path}/cards?archived=true");
19373×
            if json {
19382×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
19392×
                return Ok(0);
19401×
            }
19411×
            let mut b: hub_api::Board = c.get(&path)?;
19421×
            if archived {
19430×
                b.columns = c.get(&cards)?;
19441×
            }
19451×
            println!("{}", project_line(&b.project));
19461×
            if !b.project.description.is_empty() {
19471×
                println!("{}", b.project.description);
19481×
            }
19493×
            for col in &b.columns {
19503×
                println!();
19513×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
19523×
                if col.cards.is_empty() {
19531×
                    println!("  {}", ui::dim("(empty)"));
19542×
                }
19553×
                for card in &col.cards {
19562×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
19572×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
19582×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
19592×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
19602×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
19612×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
1962
                }
1963
            }
19641×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1965
        }
19661×
        ProjectCmd::Create { title, description, private } => {
19671×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
19681×
            if json {
19690×
                println!("{}", serde_json::to_string(&p)?);
19701×
            } else {
19711×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
19721×
            }
1973
        }
19741×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
19750×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
19760×
        ProjectCmd::Transfer { number, to } => {
19770×
            let p: hub_api::Project =
19780×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
19790×
            if json {
19800×
                println!("{}", serde_json::to_string(&p)?);
19810×
            } else {
19820×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
19830×
            }
1984
        }
19852×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1986
            // The hub names a card's issue as `repo#N` among the owner's
1987
            // repositories.
19882×
            let reference = match reference {
19891×
                None => String::new(),
19901×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
19910×
                    Some((o, rest)) if o == owner => rest.to_string(),
19920×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
19930×
                    None => r,
1994
                },
19951×
                Some(r) => {
19961×
                    let n = r.trim_start_matches('#');
19971×
                    if n.parse::<i64>().is_err() {
19980×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
19991×
                    }
20001×
                    format!("{}#{n}", t.repo()?.1)
2001
                }
2002
            };
20032×
            let note = note.unwrap_or_default();
20042×
            if reference.is_empty() && note.is_empty() {
20050×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
20062×
            }
20071×
            let card: hub_api::ProjectCard =
20082×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
20091×
            if json {
20100×
                println!("{}", serde_json::to_string(&card)?);
2011
            } else {
20121×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2013
            }
2014
        }
20151×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
20161×
            (Some(card), None) => {
20171×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
20181×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2019
            }
20200×
            (None, Some(from)) => {
20210×
                let r: hub_api::CardsMoved = c.send(
20220×
                    "POST",
20230×
                    &format!("{base}/{number}/cards/move"),
20240×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
20250×
                )?;
20260×
                if json {
20270×
                    println!("{}", serde_json::to_string(&r)?);
20280×
                    return Ok(0);
20290×
                }
20300×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
20310×
                for m in &r.moved {
20320×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2033
                }
20340×
                let verb = if dry_run { "would move" } else { "moved" };
20350×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2036
            }
20370×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2038
        },
20390×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
20400×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
20410×
                None => None,
20420×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2043
            };
20440×
            let r: hub_api::CardsArchived = c.send(
20450×
                "POST",
20460×
                &format!("{base}/{number}/cards/archive"),
20470×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
20480×
            )?;
20490×
            if json {
20500×
                println!("{}", serde_json::to_string(&r)?);
20510×
                return Ok(0);
20520×
            }
20530×
            let verb = if dry_run { "would archive" } else { "archived" };
20540×
            for a in &r.archived {
20550×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
20560×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2057
            }
20580×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2059
        }
20600×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
20610×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
20620×
            println!("{} card {card} restored", ui::ok("✔"));
2063
        }
20641×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
20651×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
20661×
            println!("{} card {card} removed", ui::ok("✔"));
2067
        }
2068
    }
20697×
    Ok(0)
207010×
}
2071
20720×
fn milestone_line(m: &hub_api::Milestone) -> String {
20730×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
20740×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
20750×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
20760×
}
2077
20780×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
20790×
    let base = t.repo_path()?;
20800×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
20810×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
20820×
        if json {
20830×
            println!("{}", serde_json::to_string(&m)?);
20840×
        } else {
20850×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
20860×
        }
20870×
        Ok(())
20880×
    };
20890×
    match cmd {
2090
        MilestoneCmd::List => {
20910×
            let path = format!("{base}/milestones");
20920×
            if json {
20930×
                println!("{}", c.get_text(&path)?);
20940×
                return Ok(0);
20950×
            }
20960×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
20970×
            if list.is_empty() {
20980×
                println!("{}", ui::dim("No milestones."));
20990×
            }
21000×
            for m in &list {
21010×
                println!("{}", milestone_line(m));
21020×
            }
2103
        }
21040×
        MilestoneCmd::Create { title, description, due } => {
21050×
            let m: hub_api::Milestone =
21060×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
21070×
            if json {
21080×
                println!("{}", serde_json::to_string(&m)?);
21090×
            } else {
21100×
                println!("{} milestone {}", ui::ok("✔"), m.title);
21110×
            }
2112
        }
21130×
        MilestoneCmd::Edit { title, rename, description, due } => {
21140×
            if rename.is_none() && description.is_none() && due.is_none() {
21150×
                bail!("say what to change: --rename, --description or --due");
21160×
            }
21170×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2118
        }
21190×
        MilestoneCmd::Close { title } => {
21200×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2121
        }
21220×
        MilestoneCmd::Reopen { title } => {
21230×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2124
        }
2125
    }
21260×
    Ok(0)
21270×
}
2128
21290×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
21300×
    let base = t.repo_path()?;
21310×
    match cmd {
2132
        TagCmd::List => {
21330×
            let path = format!("{base}/tags");
21340×
            if json {
21350×
                println!("{}", c.get_text(&path)?);
21360×
                return Ok(0);
21370×
            }
21380×
            let tags: Vec<Tag> = c.get(&path)?;
21390×
            if tags.is_empty() {
21400×
                println!("{}", ui::dim("no tags"));
21410×
            }
21420×
            for t in tags {
21430×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
21440×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
21450×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2146
            }
2147
        }
21480×
        TagCmd::Create { name, target, message } => {
21490×
            let new = hub_api::NewTag { name, target, message };
21500×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
21510×
            if json {
21520×
                println!("{}", serde_json::to_string(&made)?);
21530×
            } else {
21540×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
21550×
            }
2156
        }
21570×
        TagCmd::Delete { name, reason } => {
21580×
            let reason = reason.unwrap_or_default();
21590×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
21600×
            if json {
21610×
                println!("{}", serde_json::json!({ "withdrawn": name }));
21620×
            } else {
21630×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
21640×
            }
2165
        }
2166
    }
21670×
    Ok(0)
21680×
}
2169
21704×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
21714×
    let base = t.repo_path()?;
21724×
    match cmd {
2173
        ReleaseCmd::List => {
21741×
            let path = format!("{base}/releases");
21751×
            if json {
21761×
                println!("{}", c.get_text(&path)?);
21771×
                return Ok(0);
21780×
            }
21790×
            let list: Vec<Release> = c.get(&path)?;
21800×
            if list.is_empty() {
21810×
                println!("{}", ui::dim("No releases."));
21820×
            }
21830×
            for r in &list {
21840×
                println!(
2185
                    "{} {} {}{}",
21860×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
21870×
                    ui::strong(&r.tag),
2188
                    r.title,
21890×
                    ui::dim(&format!(
2190
                        " · {} asset{} · {}",
21910×
                        r.assets.len(),
21920×
                        if r.assets.len() == 1 { "" } else { "s" },
21930×
                        ui::ago(r.created_ms)
2194
                    ))
2195
                );
2196
            }
2197
        }
21981×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
21991×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
22001×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
22011×
            if json {
22020×
                println!("{}", serde_json::to_string(&r)?);
22031×
            } else {
22041×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22051×
            }
2206
        }
22070×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
22080×
            let notes = match notes.as_deref() {
22090×
                Some("-") => Some(body_of(None, Some("-".into()))?),
22100×
                _ => notes,
2211
            };
22120×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
22130×
                bail!("say what to change: --title, --notes or --prerelease");
22140×
            }
22150×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
22160×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
22170×
            if json {
22180×
                println!("{}", serde_json::to_string(&r)?);
22190×
            } else {
22200×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22210×
            }
2222
        }
22231×
        ReleaseCmd::Upload { tag, files } => {
22241×
            if files.is_empty() {
22250×
                bail!("name the files to attach");
22261×
            }
22271×
            for f in files {
22281×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
22291×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
22301×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
22311×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2232
            }
2233
        }
22341×
        ReleaseCmd::Trust { tag } => {
22351×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
22361×
            if json {
22370×
                println!("{}", c.get_text(&path)?);
22380×
                return Ok(0);
22391×
            }
22401×
            let r: serde_json::Value = c.get(&path)?;
22411×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
22421×
            let mut worst = 0;
22434×
            for ch in r["audit"].as_array().into_iter().flatten() {
22444×
                let v = ch["verdict"].as_str().unwrap_or("");
22454×
                worst = worst.max(match v {
22464×
                    "fail" => 2,
22474×
                    "warn" => 1,
22483×
                    _ => 0,
2249
                });
22504×
                let g = match v {
22514×
                    "pass" => ui::ok("✔"),
22521×
                    "warn" => ui::warn("!"),
22530×
                    _ => ui::bad("✘"),
2254
                };
22554×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2256
            }
22571×
            return Ok(if worst == 2 { 1 } else { 0 });
2258
        }
2259
    }
22602×
    Ok(0)
22614×
}
2262
2263
#[cfg(test)]
2264
mod tests {
2265
2266
    #[test]
22671×
    fn runner_update_scopes_resolve_by_name_or_id() {
22681×
        let all = hub_api::RunnerUpdates {
22691×
            repo: String::new(),
22701×
            settings: vec![],
22711×
            groups: vec![hub_api::RunnerGroup { id: 4, owner: "acme".into(), name: "canary".into(), percent: None, members: vec![] }],
22721×
            runners: vec![],
22731×
            holds: vec![],
22741×
        };
22751×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
22761×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
22773×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
22783×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2279
        }
22801×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
22811×
        assert!(update_scope("everyone", &all).is_err());
22821×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
22831×
        assert!(switch(Some("yes")).is_err());
22841×
    }
2285
    use super::*;
2286
2287
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2288
    /// help says, and a drop is named by its id or its address.
2289
    #[test]
22901×
    fn drop_commands_parse() {
22911×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
22921×
        match cli.cmd {
22931×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
22941×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
22951×
                assert!(secret);
22961×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2297
            }
22980×
            _ => panic!("not drop create"),
2299
        }
23001×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
23011×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
23021×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
23031×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
23041×
                assert!(channel.is_none() && dry_run.is_none());
2305
            }
23060×
            _ => panic!("not runner-updates set"),
2307
        }
23081×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
23091×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
23101×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
23110×
            _ => panic!("not drop list"),
2312
        }
23131×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
23141×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
23151×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2316
            }
23170×
            _ => panic!("not drop view"),
2318
        }
23191×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
23201×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
23211×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
23221×
        assert!(drop_id("andy/notes").is_err());
23231×
    }
2324
}