OXYGENHUB

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

551 of 1356 lines run, 35 of 192 functions · run #477 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)
335
    List {
336
        #[arg(long, default_value = "open")]
337
        state: String,
338
    },
339
    /// One proposal: its changes, approvals and whether it can land
340
    View { number: i64 },
341
    /// Propose a bookmark's changes for another bookmark
342
    Create {
343
        #[arg(long, short)]
344
        title: String,
345
        #[arg(long, short)]
346
        body: Option<String>,
347
        /// Read the body from a file ("-" for stdin)
348
        #[arg(long, short = 'F', conflicts_with = "body")]
349
        body_file: Option<String>,
350
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
351
        #[arg(long)]
352
        from: String,
353
        /// The bookmark to land them on (default: the repository's default bookmark)
354
        #[arg(long)]
355
        into: Option<String>,
356
        #[arg(long)]
357
        draft: bool,
358
    },
359
    /// Change a proposal's title or description (its author or a maintainer)
360
    Edit {
361
        number: i64,
362
        #[arg(long, short)]
363
        title: Option<String>,
364
        #[arg(long, short)]
365
        body: Option<String>,
366
        /// Read the body from a file ("-" for stdin)
367
        #[arg(long, short = 'F', conflicts_with = "body")]
368
        body_file: Option<String>,
369
    },
370
    /// Put labels on a proposal or take them off (triage)
371
    Label(LabelChange),
372
    /// Comment on a proposal's conversation
373
    Comment {
374
        number: i64,
375
        #[arg(long, short)]
376
        body: Option<String>,
377
        /// Read the comment from a file ("-" for stdin)
378
        #[arg(long, short = 'F', conflicts_with = "body")]
379
        body_file: Option<String>,
380
    },
381
    /// The checks on a proposal's projected state
382
    Checks { number: i64 },
383
    /// Land a proposal on its target, as the page's Land button does
384
    Land {
385
        number: i64,
386
        /// Land before its required checks pass, saying why (maintainers;
387
        /// recorded and audited, #261)
388
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
389
        over_checks: Option<String>,
390
        /// Land it by itself once its checks pass (#261); with --off, don't
391
        #[arg(long)]
392
        when_ready: bool,
393
        /// With --when-ready: turn it off
394
        #[arg(long, requires = "when_ready")]
395
        off: bool,
396
    },
397
    /// Close a proposal without landing it, with an optional comment
398
    Close {
399
        number: i64,
400
        /// Say why, as a comment before it closes
401
        #[arg(long, short = 'm')]
402
        message: Option<String>,
403
    },
404
    /// Reopen a closed proposal
405
    Reopen { number: i64 },
406
    /// Take a draft proposal out of draft, ready for review (its author or triage)
407
    Ready {
408
        number: i64,
409
        /// Turn an open proposal back into a draft instead
410
        #[arg(long)]
411
        undo: bool,
412
    },
413
}
414
415
#[derive(Subcommand)]
416
enum AssistantCmd {
417
    /// The assistants this level sees, its own and those inherited
418
    List,
419
    /// Add an assistant, or change the one of that name
420
    Add {
421
        /// How it shows on reviews (default: the provider's name)
422
        #[arg(long, default_value = "")]
423
        name: String,
424
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
425
        #[arg(long, default_value = "")]
426
        preset: String,
427
        /// The endpoint, when no preset or another one
428
        #[arg(long, default_value = "")]
429
        endpoint: String,
430
        /// chat-completions or anthropic-messages
431
        #[arg(long, default_value = "")]
432
        api: String,
433
        /// One the endpoint lists (`oh assistant models` shows them)
434
        #[arg(long)]
435
        model: String,
436
        /// The API key, read from this environment variable (never typed on the command line)
437
        #[arg(long, value_name = "VAR")]
438
        token_env: Option<String>,
439
        /// Add it turned off
440
        #[arg(long)]
441
        off: bool,
442
    },
443
    /// Remove this level's assistant of that name
444
    Remove { name: String },
445
    /// Show this level's prompt, and those it inherits
446
    Prompt {
447
        /// Set it from this file (`-` for standard input; an empty file clears it)
448
        #[arg(long, value_name = "FILE")]
449
        set: Option<std::path::PathBuf>,
450
    },
451
}
452
453
#[derive(Subcommand)]
454
enum LabelCmd {
455
    /// The repository's labels
456
    List,
457
    /// Create a label, or change the one of that name (triage)
458
    Create {
459
        name: String,
460
        /// `#rrggbb` (default: one the hub picks)
461
        #[arg(long)]
462
        colour: Option<String>,
463
        #[arg(long, short, default_value = "")]
464
        description: String,
465
    },
466
    /// Delete a label, taking it off every issue and proposal (triage)
467
    Delete { name: String },
468
}
469
470
#[derive(Subcommand)]
471
enum ProjectCmd {
472
    /// The owner's boards
473
    List,
474
    /// One board: its columns and cards
475
    View {
476
        number: i64,
477
        /// Its archived cards instead (#293)
478
        #[arg(long)]
479
        archived: bool,
480
    },
481
    /// Create a board (owner, or an organisation's members)
482
    Create {
483
        title: String,
484
        #[arg(long, short, default_value = "")]
485
        description: String,
486
        /// Only the owner (or the organisation's members) can see it
487
        #[arg(long)]
488
        private: bool,
489
    },
490
    /// Close a board
491
    Close { number: i64 },
492
    /// Reopen a board
493
    Reopen { number: i64 },
494
    /// Move a board to another owner you may make boards under (an
495
    /// organisation, say); it takes the next number there
496
    Transfer {
497
        number: i64,
498
        /// The new owner
499
        #[arg(long)]
500
        to: String,
501
    },
502
    /// Cards on a board: add, move, archive, restore, remove
503
    Card {
504
        #[command(subcommand)]
505
        cmd: CardCmd,
506
    },
507
}
508
509
#[derive(Subcommand)]
510
enum CardCmd {
511
    /// Put an issue or proposal on a board (`12` or `#12` in this
512
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
513
    /// or a note with --note
514
    Add {
515
        number: i64,
516
        /// The issue or proposal; a number means this repository's
517
        reference: Option<String>,
518
        /// A note card instead
519
        #[arg(long, conflicts_with = "reference")]
520
        note: Option<String>,
521
        /// The column, by name or id (default: the first)
522
        #[arg(long, short)]
523
        column: Option<String>,
524
    },
525
    /// Move a card to another column (by name or id), or with --from every
526
    /// card of a column at once
527
    Move {
528
        number: i64,
529
        /// The card (its id); leave it out with --from
530
        card: Option<i64>,
531
        #[arg(long, short)]
532
        column: String,
533
        /// Move every card of this column (#289)
534
        #[arg(long, conflicts_with = "card")]
535
        from: Option<String>,
536
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
537
        #[arg(long, value_delimiter = ',', requires = "from")]
538
        except: Vec<String>,
539
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
540
        #[arg(long, value_delimiter = ',', requires = "from")]
541
        state: Vec<String>,
542
        /// With --from: say what would move, and move nothing
543
        #[arg(long, requires = "from")]
544
        dry_run: bool,
545
    },
546
    /// Archive a column's cards: off the board, kept and restorable (#293)
547
    Archive {
548
        number: i64,
549
        /// The column, by name or id
550
        #[arg(long)]
551
        from: String,
552
        /// Only cards that joined the column more than this long ago (14d, or 14)
553
        #[arg(long)]
554
        older: Option<String>,
555
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
556
        #[arg(long, value_delimiter = ',')]
557
        except: Vec<String>,
558
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
559
        #[arg(long, value_delimiter = ',')]
560
        state: Vec<String>,
561
        /// Say what would be archived, and archive nothing
562
        #[arg(long)]
563
        dry_run: bool,
564
    },
565
    /// Put an archived card back at the end of its column
566
    Restore { number: i64, card: i64 },
567
    /// Take a card off a board
568
    Remove { number: i64, card: i64 },
569
}
570
571
#[derive(Subcommand)]
572
enum MilestoneCmd {
573
    /// The repository's milestones
574
    List,
575
    /// Create a milestone, or change the one of that title (triage)
576
    Create {
577
        title: String,
578
        #[arg(long, short, default_value = "")]
579
        description: String,
580
        /// Due date, YYYY-MM-DD
581
        #[arg(long)]
582
        due: Option<String>,
583
    },
584
    /// Change a milestone's title, description or due date (triage)
585
    Edit {
586
        title: String,
587
        #[arg(long, short)]
588
        rename: Option<String>,
589
        #[arg(long, short)]
590
        description: Option<String>,
591
        /// Due date, YYYY-MM-DD ("" for none)
592
        #[arg(long)]
593
        due: Option<String>,
594
    },
595
    /// Close a milestone
596
    Close { title: String },
597
    /// Reopen a milestone
598
    Reopen { title: String },
599
}
600
601
/// Labels to put on or take off an issue or proposal.
602
#[derive(clap::Args)]
603
struct LabelChange {
604
    number: i64,
605
    /// A label to add (repeatable)
606
    #[arg(long, short)]
607
    add: Vec<String>,
608
    /// A label to take off (repeatable)
609
    #[arg(long, short)]
610
    remove: Vec<String>,
611
}
612
613
impl LabelChange {
614
    /// The set after the change, from the one there now.
6150×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6160×
        if self.add.is_empty() && self.remove.is_empty() {
6170×
            bail!("say what to change: --add NAME or --remove NAME");
6180×
        }
6190×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6200×
        for a in &self.add {
6210×
            if !names.contains(a) {
6220×
                names.push(a.clone());
6230×
            }
624
        }
6250×
        Ok(names)
6260×
    }
627
}
628
6290×
fn label_names(labels: &[String]) -> String {
6300×
    if labels.is_empty() {
6310×
        ui::dim("no labels")
632
    } else {
6330×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
634
    }
6350×
}
636
637
#[derive(Subcommand)]
638
enum CoverageCmd {
639
    /// Upload an LCOV or Cobertura report measured on this machine, as the
640
    /// coverage of a bookmark's current state (default: the default
641
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
642
    /// not measured by a runner, and sets no check from it
643
    Upload {
644
        file: std::path::PathBuf,
645
        #[arg(long)]
646
        bookmark: Option<String>,
647
        /// A change's full hash
648
        #[arg(long, conflicts_with = "bookmark")]
649
        change: Option<String>,
650
    },
651
}
652
653
#[derive(Subcommand)]
654
enum RunCmd {
655
    /// Recent runs, newest first
656
    List {
657
        #[arg(long, default_value_t = 20)]
658
        limit: i64,
659
    },
660
    /// A run and its jobs
661
    View { number: i64 },
662
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
663
    Start {
664
        #[arg(long)]
665
        bookmark: Option<String>,
666
        /// A change's full hash
667
        #[arg(long, conflicts_with = "bookmark")]
668
        change: Option<String>,
669
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
670
        #[arg(long = "job", value_name = "NAME")]
671
        jobs: Vec<String>,
672
        /// Wait for the run and exit 1 unless it passes
673
        #[arg(long)]
674
        watch: bool,
675
    },
676
    /// Follow a run until it finishes; exit 1 unless it passes
677
    Watch { number: i64 },
678
    /// A job's log
679
    Log { number: i64, job: String },
680
    /// Run a finished run's state again; with --job, only that job (and the
681
    /// jobs that depend on it) in the same run
682
    Rerun {
683
        number: i64,
684
        #[arg(long)]
685
        job: Option<String>,
686
    },
687
    /// Cancel a run still queued or running; its running jobs are stopped
688
    Cancel { number: i64 },
689
    /// Approve a job that waits for a person (oxygenflow#57)
690
    Approve {
691
        number: i64,
692
        #[arg(long)]
693
        job: String,
694
    },
695
    /// Reject a job that waits for a person: it ends cancelled
696
    Reject {
697
        number: i64,
698
        #[arg(long)]
699
        job: String,
700
    },
701
}
702
703
#[derive(Subcommand)]
704
enum TagCmd {
705
    /// Tags, newest name first
706
    List,
707
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
708
    /// delegate (as `oxy tag create` and a push would be)
709
    Create {
710
        name: String,
711
        /// What to tag (default: the default bookmark)
712
        #[arg(long)]
713
        target: Option<String>,
714
        #[arg(long, short)]
715
        message: Option<String>,
716
    },
717
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
718
    /// their next fetch, and the name is never used again. Refused while a
719
    /// release uses the tag
720
    Delete {
721
        name: String,
722
        /// Why, recorded with the withdrawal
723
        #[arg(long, short)]
724
        reason: Option<String>,
725
    },
726
}
727
728
#[derive(Subcommand)]
729
enum ReleaseCmd {
730
    /// Releases, newest first
731
    List,
732
    /// Create a release on an existing tag
733
    Create {
734
        tag: String,
735
        #[arg(long, short)]
736
        title: Option<String>,
737
        /// Notes in Markdown (default: generated from the changes since the previous release)
738
        #[arg(long, short)]
739
        notes: Option<String>,
740
        #[arg(long)]
741
        prerelease: bool,
742
    },
743
    /// Change a release's title, notes or prerelease flag
744
    Edit {
745
        tag: String,
746
        #[arg(long, short)]
747
        title: Option<String>,
748
        /// New notes in Markdown ("-" reads them from stdin)
749
        #[arg(long, short)]
750
        notes: Option<String>,
751
        /// Mark it a prerelease (true) or not (false)
752
        #[arg(long)]
753
        prerelease: Option<bool>,
754
    },
755
    /// Attach files to a release
756
    Upload { tag: String, files: Vec<std::path::PathBuf> },
757
    /// The release's trust report: signatures, builds, receipts and audit
758
    Trust { tag: String },
759
}
760
76147×
fn main() {
762
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
763
    // other command-line tools do, instead of panicking on the failed
764
    // write (oxygenhub#92).
765
    #[cfg(unix)]
76647×
    unsafe {
76747×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
76847×
    }
76947×
    let cli = Cli::parse();
77047×
    ui::init(cli.plain);
77147×
    match run(cli) {
77240×
        Ok(code) => std::process::exit(code),
7737×
        Err(e) => {
7747×
            eprintln!("{} {e:#}", ui::bad("error:"));
7757×
            std::process::exit(2);
776
        }
777
    }
778
}
779
78017×
fn enc(s: &str) -> String {
78117×
    let mut out = String::new();
78267×
    for b in s.bytes() {
78367×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
78467×
            out.push(b as char);
78567×
        } else {
7860×
            out.push_str(&format!("%{b:02X}"));
7870×
        }
788
    }
78917×
    out
79017×
}
791
79247×
fn run(cli: Cli) -> Result<i32> {
79347×
    let cfg = Config::load()?;
7941×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
7951×
        return login(cfg, url, token.clone(), ca.clone());
79646×
    }
79746×
    let here = std::env::current_dir()?;
79846×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
79945×
    let c = Client::new(&t)?;
80045×
    let json = cli.json;
8010×
    match cli.cmd {
802
        Cmd::Auth { cmd: AuthCmd::Status } => {
8030×
            let me: serde_json::Value = c.get("/user")?;
8040×
            if json {
8050×
                println!("{me}");
8060×
            } else {
8070×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
8080×
            }
8090×
            Ok(0)
810
        }
8110×
        Cmd::Auth { .. } => unreachable!(),
8121×
        Cmd::Api { path, method, data } => {
8131×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
814
            // The method applies with or without a body (#75): without one, a
815
            // GET reads, anything else sends an empty object.
8161×
            let text = match data {
8170×
                Some(d) => c.send_text(
8180×
                    &method.to_uppercase(),
8190×
                    &path,
8200×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
8210×
                )?,
8221×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
8230×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
824
            };
8251×
            println!("{text}");
8261×
            Ok(0)
827
        }
828
        Cmd::Repo { cmd: RepoCmd::View } => {
8291×
            let path = t.repo_path()?;
8301×
            if json {
8310×
                println!("{}", c.get_text(&path)?);
8320×
                return Ok(0);
8331×
            }
8341×
            let r: serde_json::Value = c.get(&path)?;
8351×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
8361×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
8371×
                println!("{d}");
8381×
            }
8391×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
8401×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
8411×
            Ok(0)
842
        }
84315×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
8444×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
8453×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
8460×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
8470×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
8480×
            let mut body = serde_json::json!({ "content": content });
8490×
            if let Some(b) = bookmark {
8500×
                body["bookmark"] = b.into();
8510×
            }
8520×
            if let Some(ch) = change {
8530×
                body["change"] = ch.into();
8540×
            }
8550×
            let base = t.repo_path()?;
8560×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
8570×
            if json {
8580×
                println!("{}", serde_json::to_string(&r)?);
859
            } else {
8600×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
8610×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
8620×
                println!(
863
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
8640×
                    ui::ok("✔"),
865
                    r.lines_hit,
866
                    r.lines_found,
867
                    r.files,
8680×
                    ui::dim(&r.url)
869
                );
8700×
                if r.dropped > 0 {
8710×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
8720×
                }
873
            }
8740×
            Ok(0)
875
        }
8764×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
8770×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
8780×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
8790×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
88010×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
8810×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
8820×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
8830×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
8847×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
885
    }
88647×
}
887
888
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
8892×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
8902×
    Ok(match v {
8910×
        None => None,
8922×
        Some("on") => Some(Some(true)),
8932×
        Some("off") => Some(Some(false)),
8942×
        Some("inherit") => Some(None),
8951×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
896
    })
8972×
}
898
899
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
9007×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
9017×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
9021×
    Ok(match kind {
9037×
        "site" if name.is_empty() => ("site".into(), String::new()),
9046×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
9055×
        "group" => {
9063×
            let g = all
9073×
                .groups
9083×
                .iter()
9093×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
9103×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
9113×
            ("group".into(), g.id.to_string())
912
        }
9132×
        "runner" => {
9141×
            let r = all
9151×
                .runners
9161×
                .iter()
9171×
                .find(|r| r.id.to_string() == name || r.name == name)
9181×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
9190×
            ("runner".into(), r.id.to_string())
920
        }
9211×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
922
    })
9237×
}
924
9250×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
9260×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
9270×
    match cmd {
9280×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
929
        RunnerUpdatesCmd::Show => {
9300×
            println!(
931
                "{} {}",
9320×
                ui::strong("Builds from"),
9330×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
934
            );
9350×
            for h in &all.holds {
9360×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
9370×
            }
9380×
            for s in &all.settings {
9390×
                let mut said = vec![];
9400×
                if let Some(u) = s.updates {
9410×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
9420×
                }
9430×
                if let Some(ch) = &s.channel {
9440×
                    said.push(format!("channel {ch}"));
9450×
                }
9460×
                if let Some(w) = &s.window {
9470×
                    said.push(format!("window {w} UTC"));
9480×
                }
9490×
                if let Some(d) = s.dry_run {
9500×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
9510×
                }
9520×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
9530×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
954
            }
9550×
            for g in &all.groups {
9560×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
9570×
                let what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
9580×
                println!(
959
                    "  group {} ({what}): {}",
9600×
                    ui::strong(&g.name),
9610×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
962
                );
963
            }
9640×
            for r in &all.runners {
9650×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
9660×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
967
            }
968
        }
9690×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
9700×
            let (scope, key) = update_scope(&scope, &all)?;
9710×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
9720×
                scope: scope.clone(),
9730×
                key: key.clone(),
9740×
                ..Default::default()
9750×
            });
9760×
            if let Some(u) = switch(updates.as_deref())? {
9770×
                s.updates = u;
9780×
            }
9790×
            if let Some(d) = switch(dry_run.as_deref())? {
9800×
                s.dry_run = d;
9810×
            }
9820×
            if let Some(ch) = channel {
9830×
                s.channel = Some(ch).filter(|c| c != "inherit");
9840×
            }
9850×
            if let Some(w) = window {
9860×
                s.window = Some(w).filter(|w| w != "inherit");
9870×
            }
9880×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
9890×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
990
        }
9910×
        RunnerUpdatesCmd::Lift { version } => {
9920×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
9930×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
994
        }
995
    }
9960×
    Ok(0)
9970×
}
998
999
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
10007×
fn drop_id(s: &str) -> Result<String> {
10017×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1002144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
10031×
        bail!("{s:?} is not a drop's id or address");
10046×
    }
10056×
    Ok(id.to_ascii_lowercase())
10067×
}
1007
10082×
fn drop_line(d: &hub_api::Drop) -> String {
10092×
    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() };
10104×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
10112×
    format!(
1012
        "{} {} {}{}",
10132×
        ui::dim(&d.id),
10142×
        ui::strong(&title),
10152×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
10162×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1017
    )
10182×
}
1019
10207×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
10217×
    match cmd {
10221×
        DropCmd::Create { files, secret, description, title } => {
10231×
            let mut out = Vec::with_capacity(files.len());
10242×
            for f in &files {
10252×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
10262×
                let content =
10272×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
10282×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1029
            }
10301×
            let new =
10311×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
10321×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
10331×
            if json {
10341×
                println!("{}", serde_json::to_string(&d)?);
1035
            } else {
10360×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
10370×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1038
            }
1039
        }
10402×
        DropCmd::List { user } => {
10412×
            let path = match &user {
10421×
                Some(u) => format!("/users/{}/drops", enc(u)),
10431×
                None => "/drops".to_string(),
1044
            };
10452×
            if json {
10461×
                println!("{}", c.get_text(&path)?);
10471×
                return Ok(0);
10481×
            }
10491×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
10501×
            if list.is_empty() {
10510×
                println!("{}", ui::dim("No drops."));
10521×
            }
10531×
            for d in &list {
10541×
                println!("{}", drop_line(d));
10551×
            }
1056
        }
10573×
        DropCmd::View { id, file } => {
10583×
            let path = format!("/drops/{}", drop_id(&id)?);
10593×
            if json && file.is_none() {
10600×
                println!("{}", c.get_text(&path)?);
10610×
                return Ok(0);
10623×
            }
10633×
            let d: hub_api::Drop = c.get(&path)?;
10642×
            if let Some(name) = file {
10652×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
10661×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
10671×
                print!("{content}");
10681×
                return Ok(0);
10691×
            }
10701×
            println!("{}", drop_line(&d));
10711×
            if !d.description.is_empty() {
10721×
                println!("{}", d.description);
10731×
            }
10741×
            println!("{}", ui::kv("url", &d.url));
10751×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
10762×
            for f in &d.files {
10772×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
10782×
                match &f.content {
10792×
                    Some(text) => {
10802×
                        print!("{text}");
10812×
                        if !text.ends_with('\n') && !text.is_empty() {
10820×
                            println!();
10832×
                        }
1084
                    }
10850×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1086
                }
1087
            }
1088
        }
10891×
        DropCmd::Delete { id } => {
10901×
            let id = drop_id(&id)?;
10911×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
10921×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1093
        }
1094
    }
10954×
    Ok(0)
10967×
}
1097
1098
/// `30d`, `12h`, `90m` in milliseconds.
10990×
fn duration_ms(s: &str) -> Result<i64> {
11000×
    let s = s.trim();
11010×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
11020×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
11030×
    let per = match unit {
11040×
        "d" => 86_400_000,
11050×
        "h" => 3_600_000,
11060×
        "m" => 60_000,
11070×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1108
    };
11090×
    if n <= 0 {
11100×
        bail!("a grant must last some time");
11110×
    }
11120×
    Ok(n * per)
11130×
}
1114
11150×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1116
    use oxy_core::cert::{Grant, SignedGrant};
1117
    use oxy_core::identity::{Identity, Scope};
11180×
    match cmd {
11190×
        AgentCmd::Grant { name, scope, lasts } => {
11200×
            let home = oxy_core::repo::default_home();
11210×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
11220×
                format!(
1123
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
11240×
                    home.display()
1125
                )
11260×
            })?;
11270×
            let me: serde_json::Value = c.get("/user")?;
11280×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
11290×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
11300×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
11310×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11320×
            let grant = Grant {
11330×
                grantor: me_id.hash(),
11340×
                subject: format!("agent:{name}@{username}"),
11350×
                issuer: hub.hash(),
11360×
                scope,
11370×
                not_before: (now - 60_000) as u64,
11380×
                expires: (now + duration_ms(&lasts)?) as u64,
1139
            };
11400×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
11410×
            let r: serde_json::Value =
11420×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
11430×
            if json {
11440×
                println!("{r}");
11450×
                return Ok(0);
11460×
            }
11470×
            println!(
1148
                "{} {} to act for you as {} ({}), until {}",
11490×
                ui::ok("✔ granted"),
11500×
                ui::strong(&name),
11510×
                r["subject"].as_str().unwrap_or(""),
11520×
                r["scope"].as_str().unwrap_or(""),
11530×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1154
            );
11550×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
11560×
            println!(
1157
                "  {}",
11580×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1159
            );
11600×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
11610×
            Ok(0)
1162
        }
1163
        AgentCmd::List => {
11640×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
11650×
            if json {
11660×
                println!("{}", serde_json::to_string(&grants)?);
11670×
                return Ok(0);
11680×
            }
11690×
            if grants.is_empty() {
11700×
                println!("{}", ui::dim("no agent grants"));
11710×
            }
11720×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
11730×
            for g in grants {
11740×
                let state = if g["revoked_ms"].is_i64() {
11750×
                    ui::bad("revoked")
11760×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
11770×
                    ui::dim("ended")
1178
                } else {
11790×
                    ui::ok("live")
1180
                };
11810×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
11820×
                println!(
1183
                    "#{:<4} {:<8} {} · {} · until {} · {}",
11840×
                    g["id"],
1185
                    state,
11860×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
11870×
                    g["scope"].as_str().unwrap_or(""),
11880×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
11890×
                    ui::dim(&used)
1190
                );
1191
            }
11920×
            Ok(0)
1193
        }
11940×
        AgentCmd::Revoke { id } => {
11950×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
11960×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
11970×
            Ok(0)
1198
        }
1199
    }
12000×
}
1201
12021×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
12031×
    let hub = url.trim_end_matches('/').to_string();
12041×
    let token = match token.as_deref() {
12051×
        Some("-") => {
12060×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
12070×
            let mut line = String::new();
12080×
            std::io::stdin().read_line(&mut line)?;
12090×
            line.trim().to_string()
1210
        }
12111×
        Some(t) => t.to_string(),
12120×
        None => device_sign_in(&hub, ca.clone())?,
1213
    };
12141×
    if token.is_empty() {
12150×
        bail!("no token given");
12161×
    }
12171×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
12181×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
12191×
    let account = me["username"].as_str().unwrap_or("?");
1220
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
12211×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
12221×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
12231×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
12241×
    cfg.default_hub = Some(hub.clone());
12251×
    cfg.save()?;
12261×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
12271×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
12281×
    Ok(0)
12291×
}
1230
1231
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1232
/// it on the web, and the token arrives here.
12330×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
12340×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
12350×
    let c = Client::new(&t)?;
12360×
    let host = std::fs::read_to_string("/etc/hostname")
12370×
        .ok()
12380×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
12390×
        .map(|h| h.trim().to_string())
12400×
        .filter(|h| !h.is_empty());
12410×
    let client = match host {
12420×
        Some(h) => format!("oh on {h}"),
12430×
        None => "oh".to_string(),
1244
    };
12450×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
12460×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
12470×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
12480×
    if code != 200 {
12490×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
12500×
    }
12510×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
12520×
    let user = v["user_code"].as_str().unwrap_or("?");
12530×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
12540×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
12550×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
12560×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
12570×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1258
    loop {
12590×
        std::thread::sleep(std::time::Duration::from_secs(interval));
12600×
        if std::time::Instant::now() > deadline {
12610×
            bail!("the code expired before it was approved; run oh auth login again");
12620×
        }
12630×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
12640×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
12650×
        if code == 200 {
12660×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
12670×
        }
12680×
        match v["error"].as_str() {
12690×
            Some("authorization_pending") => {}
12700×
            Some("slow_down") => interval += 5,
12710×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
12720×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
12730×
            _ => bail!("signing in: HTTP {code}: {body}"),
1274
        }
1275
    }
12760×
}
1277
12787×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
12797×
    match (body, file) {
12802×
        (Some(b), _) => Ok(b),
12811×
        (None, Some(f)) if f == "-" => {
12820×
            let mut s = String::new();
12830×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
12840×
            Ok(s)
1285
        }
12861×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
12874×
        (None, None) => Ok(String::new()),
1288
    }
12897×
}
1290
12913×
fn issue_line(i: &Issue) -> String {
12923×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
12933×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
12943×
    format!(
1295
        "{glyph} {} {}{}{}",
12963×
        ui::dim(&format!("#{}", i.number)),
1297
        i.title,
12983×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
12993×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1300
    )
13013×
}
1302
130315×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
130415×
    let base = t.repo_path()?;
130515×
    match cmd {
13063×
        IssueCmd::List { state } => {
13073×
            let path = format!("{base}/issues?state={}", enc(&state));
13083×
            if json {
13091×
                println!("{}", c.get_text(&path)?);
13101×
                return Ok(0);
13112×
            }
13122×
            let list: Vec<Issue> = c.get(&path)?;
13132×
            if list.is_empty() {
13141×
                println!("{}", ui::dim(&format!("No {state} issues.")));
13151×
            }
13162×
            for i in &list {
13172×
                println!("{}", issue_line(i));
13182×
            }
1319
        }
13202×
        IssueCmd::View { number } => {
13212×
            let path = format!("{base}/issues/{number}");
13222×
            if json {
13231×
                println!("{}", c.get_text(&path)?);
13241×
                return Ok(0);
13251×
            }
13261×
            let i: Issue = c.get(&path)?;
13271×
            println!("{}", issue_line(&i));
13281×
            if !i.body.trim().is_empty() {
13291×
                println!("\n{}\n", i.body.trim_end());
13301×
            }
13311×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
13322×
            for cm in comments {
13332×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
13342×
            }
13351×
            println!("{}", ui::dim(&i.url));
1336
        }
13373×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
13383×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
13393×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
13402×
            if json {
13410×
                println!("{}", serde_json::to_string(&i)?);
13422×
            } else {
13432×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13442×
            }
13452×
            if let Some(n) = project {
13461×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
13471×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
13481×
                if !json {
13491×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
13501×
                }
13511×
            }
1352
        }
13531×
        IssueCmd::Close { number, reason } => {
13541×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
13551×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1356
        }
13570×
        IssueCmd::Reopen { number } => {
13580×
            let i: Issue =
13590×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
13600×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1361
        }
13623×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
13633×
            let body = match (&body, &body_file) {
13643×
                (None, None) => None,
13650×
                _ => Some(body_of(body, body_file)?),
1366
            };
13673×
            let labels = if no_labels {
13681×
                Some(Vec::new())
13692×
            } else if label.is_empty() {
13701×
                None
1371
            } else {
13721×
                Some(label)
1373
            };
13743×
            let assignees = if no_assignees {
13751×
                Some(Vec::new())
13762×
            } else if assignee.is_empty() {
13771×
                None
1378
            } else {
13791×
                Some(assignee)
1380
            };
13813×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
13821×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
13832×
            }
13842×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
13852×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
13862×
            if json {
13871×
                println!("{}", serde_json::to_string(&i)?);
13881×
            } else {
13891×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
13901×
            }
1391
        }
13920×
        IssueCmd::Label(change) => {
13930×
            let path = format!("{base}/issues/{}", change.number);
13940×
            let now: Issue = c.get(&path)?;
13950×
            let labels = change.apply(&now.labels)?;
13960×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
13970×
            let i: Issue = c.send("PATCH", &path, &edit)?;
13980×
            if json {
13990×
                println!("{}", serde_json::to_string(&i)?);
14000×
            } else {
14010×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
14020×
            }
1403
        }
14043×
        IssueCmd::Comment { number, body, body_file } => {
14053×
            let body = body_of(body, body_file)?;
14063×
            if body.trim().is_empty() {
14071×
                bail!("give the comment with --body or --body-file");
14082×
            }
14092×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
14102×
            println!("{} commented on #{number}", ui::ok("✔"));
1411
        }
1412
    }
141310×
    Ok(0)
141415×
}
1415
14161×
fn source_name(s: &hub_api::ProposalSource) -> String {
14171×
    match s {
14181×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
14190×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
14200×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1421
    }
14221×
}
1423
14241×
fn proposal_line(p: &Proposal) -> String {
14251×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
14261×
    let glyph = match state.as_str() {
14271×
        "open" => ui::ok("●"),
14280×
        "draft" => ui::dim("◌"),
14290×
        "landed" => ui::strong("✔"),
14300×
        _ => ui::dim("○"),
1431
    };
14321×
    format!(
1433
        "{glyph} {} {} {}{}",
14341×
        ui::dim(&format!("#{}", p.number)),
1435
        p.title,
14361×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
14371×
        ui::dim(&format!(" · {} · {state}", p.author))
1438
    )
14391×
}
1440
14414×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
14424×
    let base = t.repo_path()?;
14434×
    match cmd {
14440×
        ProposalCmd::List { state } => {
14450×
            let path = format!("{base}/proposals?state={state}");
14460×
            if json {
14470×
                println!("{}", c.get_text(&path)?);
14480×
                return Ok(0);
14490×
            }
14500×
            let list: Vec<Proposal> = c.get(&path)?;
14510×
            if list.is_empty() {
14520×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
14530×
            }
14540×
            for p in &list {
14550×
                println!("{}", proposal_line(p));
14560×
            }
1457
        }
14581×
        ProposalCmd::View { number } => {
14591×
            let path = format!("{base}/proposals/{number}");
14601×
            if json {
14610×
                println!("{}", c.get_text(&path)?);
14620×
                return Ok(0);
14631×
            }
14641×
            let p: Proposal = c.get(&path)?;
14651×
            println!("{}", proposal_line(&p));
14661×
            if !p.body.trim().is_empty() {
14670×
                println!("\n{}\n", p.body.trim_end());
14681×
            }
14691×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
14701×
            for ch in &p.changes {
14711×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
14721×
            }
14731×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
14741×
            if p.landable {
14751×
                println!("{} can land", ui::ok("✔"));
14761×
            } else {
14770×
                for b in &p.blockers {
14780×
                    println!("{} {b}", ui::bad("✘"));
14790×
                }
1480
            }
14811×
            if p.conflicted {
14820×
                println!("{} landing it would leave conflicts", ui::bad("!"));
14831×
            }
14841×
            println!("{}", ui::dim(&p.url));
1485
        }
14861×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
14871×
            let target = match into {
14880×
                Some(i) => i,
14891×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1490
            };
14911×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
14921×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
14931×
            if json {
14940×
                println!("{}", serde_json::to_string(&p)?);
14951×
            } else {
14961×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
14971×
            }
1498
        }
14990×
        ProposalCmd::Edit { number, title, body, body_file } => {
15000×
            let body = match (&body, &body_file) {
15010×
                (None, None) => None,
15020×
                _ => Some(body_of(body, body_file)?),
1503
            };
15040×
            if title.is_none() && body.is_none() {
15050×
                bail!("say what to change: --title, --body or --body-file");
15060×
            }
15070×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
15080×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15090×
            if json {
15100×
                println!("{}", serde_json::to_string(&p)?);
15110×
            } else {
15120×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
15130×
            }
1514
        }
15150×
        ProposalCmd::Label(change) => {
15160×
            let path = format!("{base}/proposals/{}", change.number);
15170×
            let now: Proposal = c.get(&path)?;
15180×
            let labels = change.apply(&now.labels)?;
15190×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
15200×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
15210×
            if json {
15220×
                println!("{}", serde_json::to_string(&p)?);
15230×
            } else {
15240×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
15250×
            }
1526
        }
15270×
        ProposalCmd::Comment { number, body, body_file } => {
15280×
            let body = body_of(body, body_file)?;
15290×
            if body.trim().is_empty() {
15300×
                bail!("give the comment with --body or --body-file");
15310×
            }
15320×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15330×
            println!("{} commented on #{number}", ui::ok("✔"));
1534
        }
15350×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
15360×
            let path = format!("{base}/proposals/{number}/auto-land");
15370×
            let p: Proposal =
15380×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
15390×
            if json {
15400×
                println!("{}", serde_json::to_string(&p)?);
15410×
            } else if p.landed.is_some() {
15420×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
15430×
            } else if p.auto_land.is_some() {
15440×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
15450×
            } else {
15460×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
15470×
            }
1548
        }
15492×
        ProposalCmd::Land { number, over_checks, .. } => {
15502×
            let body = match &over_checks {
15510×
                Some(r) => serde_json::json!({ "over_checks": r }),
15522×
                None => serde_json::json!({}),
1553
            };
15542×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
15551×
            if json {
15560×
                println!("{}", serde_json::to_string(&p)?);
15571×
            } else {
15581×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
15591×
            }
1560
        }
15610×
        ProposalCmd::Close { number, message } => {
15620×
            if let Some(body) = message {
15630×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
15640×
            }
15650×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
15660×
            if json {
15670×
                println!("{}", serde_json::to_string(&p)?);
15680×
            } else {
15690×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
15700×
            }
1571
        }
15720×
        ProposalCmd::Reopen { number } => {
15730×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
15740×
            if json {
15750×
                println!("{}", serde_json::to_string(&p)?);
15760×
            } else {
15770×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
15780×
            }
1579
        }
15800×
        ProposalCmd::Ready { number, undo } => {
15810×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
15820×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
15830×
            if json {
15840×
                println!("{}", serde_json::to_string(&p)?);
15850×
            } else if undo {
15860×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
15870×
            } else {
15880×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
15890×
            }
1590
        }
15910×
        ProposalCmd::Checks { number } => {
15920×
            let path = format!("{base}/proposals/{number}/checks");
15930×
            if json {
15940×
                println!("{}", c.get_text(&path)?);
15950×
                return Ok(0);
15960×
            }
15970×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
15980×
            if checks.is_empty() {
15990×
                println!("{}", ui::dim("No checks yet."));
16000×
            }
16010×
            for ch in checks {
16020×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
16030×
            }
1604
        }
1605
    }
16063×
    Ok(0)
16074×
}
1608
16091×
fn run_line(r: &FlowRun) -> String {
16101×
    let what =
16111×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
16121×
    format!(
1613
        "{} {} {} {}",
16141×
        ui::status(&r.status),
16151×
        ui::dim(&format!("#{}", r.number)),
1616
        what,
16171×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1618
    )
16191×
}
1620
16211×
fn print_run(r: &FlowRun) {
16221×
    println!("{}", run_line(r));
16231×
    for j in &r.jobs {
16241×
        let dur = match (j.started_ms, j.finished_ms) {
16250×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
16261×
            _ => String::new(),
1627
        };
16281×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
16291×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1630
        // Why a queued job no runner can take waits (oxygenhub#28), and
1631
        // why a job ran where it did (oxygenflow#42).
16321×
        if j.status == "queued" && !j.waiting.is_empty() {
16330×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
16341×
        } else if !j.placed.is_empty() {
16350×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
16361×
        }
1637
    }
16381×
    if !r.error.is_empty() {
16390×
        println!("{}", ui::bad(&r.error));
16401×
    }
16411×
    println!("{}", ui::dim(&r.url));
16421×
}
1643
16440×
fn live(status: &str) -> bool {
16450×
    matches!(status, "queued" | "running")
16460×
}
1647
1648
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
16490×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
16500×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
16510×
    if json {
16520×
        println!("{done}");
16530×
    } else {
16540×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
16550×
    }
16560×
    Ok(())
16570×
}
1658
16590×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
16600×
    let path = format!("{base}/flow/runs/{number}");
16610×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1662
    loop {
16630×
        let r: FlowRun = c.get(&path)?;
16640×
        if !json {
16650×
            for j in &r.jobs {
16660×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
16670×
                if seen.get(&j.name) != Some(&shown) {
16680×
                    println!("{} {}", ui::status(&j.status), j.name);
16690×
                    if j.status == "queued" && !j.waiting.is_empty() {
16700×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
16710×
                    }
16720×
                    seen.insert(j.name.clone(), shown);
16730×
                }
1674
            }
16750×
        }
16760×
        if !live(&r.status) {
16770×
            if json {
16780×
                println!("{}", serde_json::to_string(&r)?);
16790×
            } else {
16800×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
16810×
            }
16820×
            return Ok(if r.status == "passed" { 0 } else { 1 });
16830×
        }
16840×
        std::thread::sleep(Duration::from_secs(3));
1685
    }
16860×
}
1687
16883×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
16893×
    let base = t.repo_path()?;
16900×
    match cmd {
16911×
        RunCmd::List { limit } => {
16921×
            let path = format!("{base}/flow/runs?limit={limit}");
16931×
            if json {
16941×
                println!("{}", c.get_text(&path)?);
16951×
                return Ok(0);
16960×
            }
16970×
            let runs: Vec<FlowRun> = c.get(&path)?;
16980×
            if runs.is_empty() {
16990×
                println!("{}", ui::dim("No runs yet."));
17000×
            }
17010×
            for r in &runs {
17020×
                println!("{}", run_line(r));
17030×
            }
1704
        }
17051×
        RunCmd::View { number } => {
17061×
            let path = format!("{base}/flow/runs/{number}");
17071×
            if json {
17080×
                println!("{}", c.get_text(&path)?);
17090×
                return Ok(0);
17101×
            }
17111×
            print_run(&c.get(&path)?);
1712
        }
17131×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
17141×
            let mut body = match (bookmark, change) {
17150×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
17160×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
17171×
                (None, None) => serde_json::json!({}),
1718
            };
17191×
            if !jobs.is_empty() {
17200×
                body["jobs"] = serde_json::json!(jobs);
17211×
            }
17221×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
17231×
            let n = started["number"].as_i64().context("the hub named no run")?;
17241×
            if !json || !follow {
17251×
                if json {
17260×
                    println!("{started}");
17271×
                } else {
17281×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
17291×
                }
17300×
            }
17311×
            if follow {
17320×
                return watch(c, &base, n, json);
17331×
            }
1734
        }
17350×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
17360×
        RunCmd::Log { number, job } => {
17370×
            let mut after = 0;
1738
            loop {
17390×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
17400×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
17410×
                if lines.is_empty() {
17420×
                    break;
17430×
                }
17440×
                for l in &lines {
17450×
                    if json {
17460×
                        println!("{}", serde_json::to_string(l)?);
17470×
                    } else if l.stream == "flow" {
17480×
                        println!("{}", ui::dim(&l.text));
17490×
                    } else {
17500×
                        println!("{}", l.text);
17510×
                    }
1752
                }
17530×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1754
            }
1755
        }
17560×
        RunCmd::Rerun { number, job: Some(job) } => {
17570×
            let queued: serde_json::Value =
17580×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
17590×
            if json {
17600×
                println!("{queued}");
17610×
            } else {
17620×
                let n = queued["queued"].as_i64().unwrap_or(1);
17630×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
17640×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1765
            }
1766
        }
17670×
        RunCmd::Rerun { number, job: None } => {
17680×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
17690×
            if json {
17700×
                println!("{started}");
17710×
            } else {
17720×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
17730×
            }
1774
        }
17750×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
17760×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
17770×
        RunCmd::Cancel { number } => {
17780×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
17790×
            if json {
17800×
                println!("{done}");
17810×
            } else {
17820×
                println!("{} cancelled run #{number}", ui::ok("✔"));
17830×
            }
1784
        }
1785
    }
17862×
    Ok(0)
17873×
}
1788
17890×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
17900×
    let base = t.repo_path()?;
17910×
    match cmd {
1792
        LabelCmd::List => {
17930×
            let path = format!("{base}/labels");
17940×
            if json {
17950×
                println!("{}", c.get_text(&path)?);
17960×
                return Ok(0);
17970×
            }
17980×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
17990×
            if labels.is_empty() {
18000×
                println!("{}", ui::dim("No labels."));
18010×
            }
18020×
            for l in labels {
18030×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
18040×
            }
1805
        }
18060×
        LabelCmd::Create { name, colour, description } => {
18070×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
18080×
            if json {
18090×
                println!("{}", serde_json::to_string(&l)?);
18100×
            } else {
18110×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
18120×
            }
1813
        }
18140×
        LabelCmd::Delete { name } => {
18150×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
18160×
            println!("{} deleted label {name}", ui::ok("✔"));
1817
        }
1818
    }
18190×
    Ok(0)
18200×
}
1821
18220×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
18230×
    let base = match (&org, site) {
18240×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
18250×
        (None, true) => "/admin/assistants".to_string(),
18260×
        (None, false) => format!("{}/assistants", t.repo_path()?),
1827
    };
18280×
    match cmd {
1829
        AssistantCmd::List => {
18300×
            if json {
18310×
                println!("{}", c.get_text(&base)?);
18320×
                return Ok(0);
18330×
            }
18340×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
18350×
            if list.is_empty() {
18360×
                println!("{}", ui::dim("No assistants."));
18370×
            }
18380×
            for a in list {
18390×
                let state = if a.enabled && !a.off_above {
18400×
                    ui::ok("on")
18410×
                } else if a.off_above {
18420×
                    ui::dim("off above")
1843
                } else {
18440×
                    ui::dim("off")
1845
                };
18460×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
18470×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1848
            }
1849
        }
18500×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
18510×
            let token = match token_env {
18520×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
18530×
                None => String::new(),
1854
            };
18550×
            let body =
18560×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
18570×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
18580×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1859
        }
18600×
        AssistantCmd::Remove { name } => {
18610×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
18620×
            println!("{} removed {name}", ui::ok("✔"));
1863
        }
18640×
        AssistantCmd::Prompt { set } => {
18650×
            let p: hub_api::AssistantPrompt = match set {
18660×
                Some(path) => {
18670×
                    let text = if path.as_os_str() == "-" {
18680×
                        let mut s = String::new();
18690×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
18700×
                        s
1871
                    } else {
18720×
                        std::fs::read_to_string(&path)?
1873
                    };
18740×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1875
                }
18760×
                None => c.get(&format!("{base}/prompt"))?,
1877
            };
18780×
            if json {
18790×
                println!("{}", serde_json::to_string(&p)?);
18800×
                return Ok(0);
18810×
            }
18820×
            for (from, text) in &p.inherited {
18830×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
18840×
            }
18850×
            if p.prompt.is_empty() {
18860×
                println!("{}", ui::dim("No prompt of its own."));
18870×
            } else {
18880×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
18890×
            }
1890
        }
1891
    }
18920×
    Ok(0)
18930×
}
1894
18952×
fn project_line(p: &hub_api::Project) -> String {
18962×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
18972×
    let private = if p.public { "" } else { " · private" };
18982×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
18992×
}
1900
190110×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
190210×
    let owner = match owner {
19030×
        Some(o) => o,
190410×
        None => t.repo()?.0.to_string(),
1905
    };
190610×
    let base = format!("/projects/{}", enc(&owner));
190710×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
19081×
        let p: hub_api::Project =
19091×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
19101×
        if json {
19110×
            println!("{}", serde_json::to_string(&p)?);
19121×
        } else {
19131×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
19141×
        }
19151×
        Ok(())
19161×
    };
19174×
    match cmd {
1918
        ProjectCmd::List => {
19191×
            if json {
19200×
                println!("{}", c.get_text(&base)?);
19210×
                return Ok(0);
19221×
            }
19231×
            let list: Vec<hub_api::Project> = c.get(&base)?;
19241×
            if list.is_empty() {
19250×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
19261×
            }
19271×
            for p in &list {
19281×
                println!("{}", project_line(p));
19291×
            }
1930
        }
19313×
        ProjectCmd::View { number, archived } => {
19323×
            let path = format!("{base}/{number}");
19333×
            let cards = format!("{path}/cards?archived=true");
19343×
            if json {
19352×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
19362×
                return Ok(0);
19371×
            }
19381×
            let mut b: hub_api::Board = c.get(&path)?;
19391×
            if archived {
19400×
                b.columns = c.get(&cards)?;
19411×
            }
19421×
            println!("{}", project_line(&b.project));
19431×
            if !b.project.description.is_empty() {
19441×
                println!("{}", b.project.description);
19451×
            }
19463×
            for col in &b.columns {
19473×
                println!();
19483×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
19493×
                if col.cards.is_empty() {
19501×
                    println!("  {}", ui::dim("(empty)"));
19512×
                }
19523×
                for card in &col.cards {
19532×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
19542×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
19552×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
19562×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
19572×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
19582×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
1959
                }
1960
            }
19611×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1962
        }
19631×
        ProjectCmd::Create { title, description, private } => {
19641×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
19651×
            if json {
19660×
                println!("{}", serde_json::to_string(&p)?);
19671×
            } else {
19681×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
19691×
            }
1970
        }
19711×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
19720×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
19730×
        ProjectCmd::Transfer { number, to } => {
19740×
            let p: hub_api::Project =
19750×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
19760×
            if json {
19770×
                println!("{}", serde_json::to_string(&p)?);
19780×
            } else {
19790×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
19800×
            }
1981
        }
19822×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1983
            // The hub names a card's issue as `repo#N` among the owner's
1984
            // repositories.
19852×
            let reference = match reference {
19861×
                None => String::new(),
19871×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
19880×
                    Some((o, rest)) if o == owner => rest.to_string(),
19890×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
19900×
                    None => r,
1991
                },
19921×
                Some(r) => {
19931×
                    let n = r.trim_start_matches('#');
19941×
                    if n.parse::<i64>().is_err() {
19950×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
19961×
                    }
19971×
                    format!("{}#{n}", t.repo()?.1)
1998
                }
1999
            };
20002×
            let note = note.unwrap_or_default();
20012×
            if reference.is_empty() && note.is_empty() {
20020×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
20032×
            }
20041×
            let card: hub_api::ProjectCard =
20052×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
20061×
            if json {
20070×
                println!("{}", serde_json::to_string(&card)?);
2008
            } else {
20091×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2010
            }
2011
        }
20121×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
20131×
            (Some(card), None) => {
20141×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
20151×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2016
            }
20170×
            (None, Some(from)) => {
20180×
                let r: hub_api::CardsMoved = c.send(
20190×
                    "POST",
20200×
                    &format!("{base}/{number}/cards/move"),
20210×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
20220×
                )?;
20230×
                if json {
20240×
                    println!("{}", serde_json::to_string(&r)?);
20250×
                    return Ok(0);
20260×
                }
20270×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
20280×
                for m in &r.moved {
20290×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2030
                }
20310×
                let verb = if dry_run { "would move" } else { "moved" };
20320×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2033
            }
20340×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2035
        },
20360×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
20370×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
20380×
                None => None,
20390×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2040
            };
20410×
            let r: hub_api::CardsArchived = c.send(
20420×
                "POST",
20430×
                &format!("{base}/{number}/cards/archive"),
20440×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
20450×
            )?;
20460×
            if json {
20470×
                println!("{}", serde_json::to_string(&r)?);
20480×
                return Ok(0);
20490×
            }
20500×
            let verb = if dry_run { "would archive" } else { "archived" };
20510×
            for a in &r.archived {
20520×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
20530×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2054
            }
20550×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2056
        }
20570×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
20580×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
20590×
            println!("{} card {card} restored", ui::ok("✔"));
2060
        }
20611×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
20621×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
20631×
            println!("{} card {card} removed", ui::ok("✔"));
2064
        }
2065
    }
20667×
    Ok(0)
206710×
}
2068
20690×
fn milestone_line(m: &hub_api::Milestone) -> String {
20700×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
20710×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
20720×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
20730×
}
2074
20750×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
20760×
    let base = t.repo_path()?;
20770×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
20780×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
20790×
        if json {
20800×
            println!("{}", serde_json::to_string(&m)?);
20810×
        } else {
20820×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
20830×
        }
20840×
        Ok(())
20850×
    };
20860×
    match cmd {
2087
        MilestoneCmd::List => {
20880×
            let path = format!("{base}/milestones");
20890×
            if json {
20900×
                println!("{}", c.get_text(&path)?);
20910×
                return Ok(0);
20920×
            }
20930×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
20940×
            if list.is_empty() {
20950×
                println!("{}", ui::dim("No milestones."));
20960×
            }
20970×
            for m in &list {
20980×
                println!("{}", milestone_line(m));
20990×
            }
2100
        }
21010×
        MilestoneCmd::Create { title, description, due } => {
21020×
            let m: hub_api::Milestone =
21030×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
21040×
            if json {
21050×
                println!("{}", serde_json::to_string(&m)?);
21060×
            } else {
21070×
                println!("{} milestone {}", ui::ok("✔"), m.title);
21080×
            }
2109
        }
21100×
        MilestoneCmd::Edit { title, rename, description, due } => {
21110×
            if rename.is_none() && description.is_none() && due.is_none() {
21120×
                bail!("say what to change: --rename, --description or --due");
21130×
            }
21140×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2115
        }
21160×
        MilestoneCmd::Close { title } => {
21170×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2118
        }
21190×
        MilestoneCmd::Reopen { title } => {
21200×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2121
        }
2122
    }
21230×
    Ok(0)
21240×
}
2125
21260×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
21270×
    let base = t.repo_path()?;
21280×
    match cmd {
2129
        TagCmd::List => {
21300×
            let path = format!("{base}/tags");
21310×
            if json {
21320×
                println!("{}", c.get_text(&path)?);
21330×
                return Ok(0);
21340×
            }
21350×
            let tags: Vec<Tag> = c.get(&path)?;
21360×
            if tags.is_empty() {
21370×
                println!("{}", ui::dim("no tags"));
21380×
            }
21390×
            for t in tags {
21400×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
21410×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
21420×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2143
            }
2144
        }
21450×
        TagCmd::Create { name, target, message } => {
21460×
            let new = hub_api::NewTag { name, target, message };
21470×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
21480×
            if json {
21490×
                println!("{}", serde_json::to_string(&made)?);
21500×
            } else {
21510×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
21520×
            }
2153
        }
21540×
        TagCmd::Delete { name, reason } => {
21550×
            let reason = reason.unwrap_or_default();
21560×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
21570×
            if json {
21580×
                println!("{}", serde_json::json!({ "withdrawn": name }));
21590×
            } else {
21600×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
21610×
            }
2162
        }
2163
    }
21640×
    Ok(0)
21650×
}
2166
21674×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
21684×
    let base = t.repo_path()?;
21694×
    match cmd {
2170
        ReleaseCmd::List => {
21711×
            let path = format!("{base}/releases");
21721×
            if json {
21731×
                println!("{}", c.get_text(&path)?);
21741×
                return Ok(0);
21750×
            }
21760×
            let list: Vec<Release> = c.get(&path)?;
21770×
            if list.is_empty() {
21780×
                println!("{}", ui::dim("No releases."));
21790×
            }
21800×
            for r in &list {
21810×
                println!(
2182
                    "{} {} {}{}",
21830×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
21840×
                    ui::strong(&r.tag),
2185
                    r.title,
21860×
                    ui::dim(&format!(
2187
                        " · {} asset{} · {}",
21880×
                        r.assets.len(),
21890×
                        if r.assets.len() == 1 { "" } else { "s" },
21900×
                        ui::ago(r.created_ms)
2191
                    ))
2192
                );
2193
            }
2194
        }
21951×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
21961×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
21971×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
21981×
            if json {
21990×
                println!("{}", serde_json::to_string(&r)?);
22001×
            } else {
22011×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22021×
            }
2203
        }
22040×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
22050×
            let notes = match notes.as_deref() {
22060×
                Some("-") => Some(body_of(None, Some("-".into()))?),
22070×
                _ => notes,
2208
            };
22090×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
22100×
                bail!("say what to change: --title, --notes or --prerelease");
22110×
            }
22120×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
22130×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
22140×
            if json {
22150×
                println!("{}", serde_json::to_string(&r)?);
22160×
            } else {
22170×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
22180×
            }
2219
        }
22201×
        ReleaseCmd::Upload { tag, files } => {
22211×
            if files.is_empty() {
22220×
                bail!("name the files to attach");
22231×
            }
22241×
            for f in files {
22251×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
22261×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
22271×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
22281×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2229
            }
2230
        }
22311×
        ReleaseCmd::Trust { tag } => {
22321×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
22331×
            if json {
22340×
                println!("{}", c.get_text(&path)?);
22350×
                return Ok(0);
22361×
            }
22371×
            let r: serde_json::Value = c.get(&path)?;
22381×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
22391×
            let mut worst = 0;
22404×
            for ch in r["audit"].as_array().into_iter().flatten() {
22414×
                let v = ch["verdict"].as_str().unwrap_or("");
22424×
                worst = worst.max(match v {
22434×
                    "fail" => 2,
22444×
                    "warn" => 1,
22453×
                    _ => 0,
2246
                });
22474×
                let g = match v {
22484×
                    "pass" => ui::ok("✔"),
22491×
                    "warn" => ui::warn("!"),
22500×
                    _ => ui::bad("✘"),
2251
                };
22524×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2253
            }
22541×
            return Ok(if worst == 2 { 1 } else { 0 });
2255
        }
2256
    }
22572×
    Ok(0)
22584×
}
2259
2260
#[cfg(test)]
2261
mod tests {
2262
2263
    #[test]
22641×
    fn runner_update_scopes_resolve_by_name_or_id() {
22651×
        let all = hub_api::RunnerUpdates {
22661×
            repo: String::new(),
22671×
            settings: vec![],
22681×
            groups: vec![hub_api::RunnerGroup { id: 4, owner: "acme".into(), name: "canary".into(), percent: None, members: vec![] }],
22691×
            runners: vec![],
22701×
            holds: vec![],
22711×
        };
22721×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
22731×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
22743×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
22753×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2276
        }
22771×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
22781×
        assert!(update_scope("everyone", &all).is_err());
22791×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
22801×
        assert!(switch(Some("yes")).is_err());
22811×
    }
2282
    use super::*;
2283
2284
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2285
    /// help says, and a drop is named by its id or its address.
2286
    #[test]
22871×
    fn drop_commands_parse() {
22881×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
22891×
        match cli.cmd {
22901×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
22911×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
22921×
                assert!(secret);
22931×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2294
            }
22950×
            _ => panic!("not drop create"),
2296
        }
22971×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
22981×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
22991×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
23001×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
23011×
                assert!(channel.is_none() && dry_run.is_none());
2302
            }
23030×
            _ => panic!("not runner-updates set"),
2304
        }
23051×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
23061×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
23071×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
23080×
            _ => panic!("not drop list"),
2309
        }
23101×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
23111×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
23121×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2313
            }
23140×
            _ => panic!("not drop view"),
2315
        }
23161×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
23171×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
23181×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
23191×
        assert!(drop_id("andy/notes").is_err());
23201×
    }
2321
}