OXYGENHUB

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

500 of 1233 lines run, 30 of 167 functions · run #473 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
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
124
    Api {
125
        /// A path under /api/v1
126
        path: String,
127
        /// The method
128
        #[arg(long, short = 'X', default_value = "GET")]
129
        method: String,
130
        /// A JSON body
131
        #[arg(long, short = 'd')]
132
        data: Option<String>,
133
    },
134
}
135
136
#[derive(Subcommand)]
137
enum AgentCmd {
138
    /// Let an agent act for you: your oxy key (the one your oxy home names
139
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
140
    /// the agent a token it exchanges for ten-minute certificates. The
141
    /// token is printed once: give it to the agent (`oxy auth grant`)
142
    Grant {
143
        /// The agent's name, as in agent:NAME@YOU
144
        name: String,
145
        /// What its keys may do for you: changes, seal, refs
146
        #[arg(long, default_value = "changes,seal,refs")]
147
        scope: String,
148
        /// How long the grant lasts: 30d, 12h, 90m
149
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
150
        lasts: String,
151
    },
152
    /// Your grants, live and past
153
    List,
154
    /// Stop a grant at once: no more certificates under it
155
    Revoke { id: i64 },
156
}
157
158
#[derive(Subcommand)]
159
enum DropCmd {
160
    /// Make a drop of these files, signed by the hub as your delegate
161
    Create {
162
        /// The files (their names in the drop are their file names)
163
        #[arg(required = true)]
164
        files: Vec<std::path::PathBuf>,
165
        /// Unlisted: readable by anyone with its address, listed nowhere
166
        #[arg(long)]
167
        secret: bool,
168
        /// A description
169
        #[arg(long, short = 'd', value_name = "TEXT")]
170
        description: Option<String>,
171
        /// A title (default: the first file's name)
172
        #[arg(long, short = 't')]
173
        title: Option<String>,
174
    },
175
    /// Your drops, or someone's public ones
176
    List {
177
        /// Whose drops
178
        #[arg(long, short = 'u', value_name = "NAME")]
179
        user: Option<String>,
180
    },
181
    /// A drop's files, printed (by id or address)
182
    View {
183
        /// The drop's id, or its address
184
        id: String,
185
        /// Print only this file's content
186
        #[arg(long, short = 'f', value_name = "NAME")]
187
        file: Option<String>,
188
    },
189
    /// Delete a drop and its history
190
    Delete {
191
        /// The drop's id, or its address
192
        id: String,
193
    },
194
}
195
196
#[derive(Subcommand)]
197
enum AuthCmd {
198
    /// Sign in to a hub and make it the default: approve a code on the web
199
    /// (device sign-in), or give a token
200
    Login {
201
        /// The hub, e.g. https://oxygenhub.io
202
        #[arg(long = "with-hub", value_name = "URL")]
203
        url: String,
204
        /// An API token from the hub's Settings → Tokens, instead of
205
        /// approving a code ("-" reads it from stdin)
206
        #[arg(long)]
207
        token: Option<String>,
208
        /// The hub's CA certificate, when self-signed
209
        #[arg(long)]
210
        ca: Option<std::path::PathBuf>,
211
    },
212
    /// Who the token in use belongs to
213
    Status,
214
}
215
216
#[derive(Subcommand)]
217
enum RepoCmd {
218
    /// Name, description, visibility and default bookmark
219
    View,
220
}
221
222
#[derive(Subcommand)]
223
enum IssueCmd {
224
    /// Put labels on an issue or take them off (triage)
225
    Label(LabelChange),
226
    /// Open issues (or --state closed|all)
227
    List {
228
        #[arg(long, default_value = "open")]
229
        state: String,
230
    },
231
    /// One issue with its comments
232
    View { number: i64 },
233
    /// Open an issue
234
    Create {
235
        #[arg(long, short)]
236
        title: String,
237
        #[arg(long, short)]
238
        body: Option<String>,
239
        /// Read the body from a file ("-" for stdin)
240
        #[arg(long, short = 'F')]
241
        body_file: Option<String>,
242
        /// A label (repeatable)
243
        #[arg(long, short)]
244
        label: Vec<String>,
245
        /// Also put it on this board of the repository's owner
246
        #[arg(long, short)]
247
        project: Option<i64>,
248
        /// The board's column for it, by name (default: the first)
249
        #[arg(long, requires = "project")]
250
        column: Option<String>,
251
    },
252
    /// Close an issue
253
    Close {
254
        number: i64,
255
        /// `completed` or `not_planned`
256
        #[arg(long, default_value = "completed")]
257
        reason: String,
258
    },
259
    /// Reopen an issue
260
    Reopen { number: i64 },
261
    /// Change an issue's title or body (its author or triage), or its
262
    /// labels, assignees or milestone as whole sets (triage)
263
    Edit {
264
        number: i64,
265
        #[arg(long, short)]
266
        title: Option<String>,
267
        #[arg(long, short)]
268
        body: Option<String>,
269
        /// Read the body from a file ("-" for stdin)
270
        #[arg(long, short = 'F', conflicts_with = "body")]
271
        body_file: Option<String>,
272
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
273
        #[arg(long, short)]
274
        label: Vec<String>,
275
        /// Clear its labels
276
        #[arg(long, conflicts_with = "label")]
277
        no_labels: bool,
278
        /// The users it should be assigned to (repeatable)
279
        #[arg(long, short)]
280
        assignee: Vec<String>,
281
        /// Take everyone off it
282
        #[arg(long, conflicts_with = "assignee")]
283
        no_assignees: bool,
284
        /// A milestone's title ("" takes it out of its milestone)
285
        #[arg(long, short)]
286
        milestone: Option<String>,
287
    },
288
    /// Comment on an issue
289
    Comment {
290
        number: i64,
291
        #[arg(long, short)]
292
        body: Option<String>,
293
        /// Read the body from a file ("-" for stdin), as proposal comment
294
        /// does (#260)
295
        #[arg(long, short = 'F', conflicts_with = "body")]
296
        body_file: Option<String>,
297
    },
298
}
299
300
#[derive(Subcommand)]
301
enum ProposalCmd {
302
    /// Open proposals (or --state draft|landed|closed|all)
303
    List {
304
        #[arg(long, default_value = "open")]
305
        state: String,
306
    },
307
    /// One proposal: its changes, approvals and whether it can land
308
    View { number: i64 },
309
    /// Propose a bookmark's changes for another bookmark
310
    Create {
311
        #[arg(long, short)]
312
        title: String,
313
        #[arg(long, short)]
314
        body: Option<String>,
315
        /// Read the body from a file ("-" for stdin)
316
        #[arg(long, short = 'F', conflicts_with = "body")]
317
        body_file: Option<String>,
318
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
319
        #[arg(long)]
320
        from: String,
321
        /// The bookmark to land them on (default: the repository's default bookmark)
322
        #[arg(long)]
323
        into: Option<String>,
324
        #[arg(long)]
325
        draft: bool,
326
    },
327
    /// Change a proposal's title or description (its author or a maintainer)
328
    Edit {
329
        number: i64,
330
        #[arg(long, short)]
331
        title: Option<String>,
332
        #[arg(long, short)]
333
        body: Option<String>,
334
        /// Read the body from a file ("-" for stdin)
335
        #[arg(long, short = 'F', conflicts_with = "body")]
336
        body_file: Option<String>,
337
    },
338
    /// Put labels on a proposal or take them off (triage)
339
    Label(LabelChange),
340
    /// Comment on a proposal's conversation
341
    Comment {
342
        number: i64,
343
        #[arg(long, short)]
344
        body: Option<String>,
345
        /// Read the comment from a file ("-" for stdin)
346
        #[arg(long, short = 'F', conflicts_with = "body")]
347
        body_file: Option<String>,
348
    },
349
    /// The checks on a proposal's projected state
350
    Checks { number: i64 },
351
    /// Land a proposal on its target, as the page's Land button does
352
    Land {
353
        number: i64,
354
        /// Land before its required checks pass, saying why (maintainers;
355
        /// recorded and audited, #261)
356
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
357
        over_checks: Option<String>,
358
        /// Land it by itself once its checks pass (#261); with --off, don't
359
        #[arg(long)]
360
        when_ready: bool,
361
        /// With --when-ready: turn it off
362
        #[arg(long, requires = "when_ready")]
363
        off: bool,
364
    },
365
    /// Close a proposal without landing it, with an optional comment
366
    Close {
367
        number: i64,
368
        /// Say why, as a comment before it closes
369
        #[arg(long, short = 'm')]
370
        message: Option<String>,
371
    },
372
    /// Reopen a closed proposal
373
    Reopen { number: i64 },
374
    /// Take a draft proposal out of draft, ready for review (its author or triage)
375
    Ready {
376
        number: i64,
377
        /// Turn an open proposal back into a draft instead
378
        #[arg(long)]
379
        undo: bool,
380
    },
381
}
382
383
#[derive(Subcommand)]
384
enum AssistantCmd {
385
    /// The assistants this level sees, its own and those inherited
386
    List,
387
    /// Add an assistant, or change the one of that name
388
    Add {
389
        /// How it shows on reviews (default: the provider's name)
390
        #[arg(long, default_value = "")]
391
        name: String,
392
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
393
        #[arg(long, default_value = "")]
394
        preset: String,
395
        /// The endpoint, when no preset or another one
396
        #[arg(long, default_value = "")]
397
        endpoint: String,
398
        /// chat-completions or anthropic-messages
399
        #[arg(long, default_value = "")]
400
        api: String,
401
        /// One the endpoint lists (`oh assistant models` shows them)
402
        #[arg(long)]
403
        model: String,
404
        /// The API key, read from this environment variable (never typed on the command line)
405
        #[arg(long, value_name = "VAR")]
406
        token_env: Option<String>,
407
        /// Add it turned off
408
        #[arg(long)]
409
        off: bool,
410
    },
411
    /// Remove this level's assistant of that name
412
    Remove { name: String },
413
    /// Show this level's prompt, and those it inherits
414
    Prompt {
415
        /// Set it from this file (`-` for standard input; an empty file clears it)
416
        #[arg(long, value_name = "FILE")]
417
        set: Option<std::path::PathBuf>,
418
    },
419
}
420
421
#[derive(Subcommand)]
422
enum LabelCmd {
423
    /// The repository's labels
424
    List,
425
    /// Create a label, or change the one of that name (triage)
426
    Create {
427
        name: String,
428
        /// `#rrggbb` (default: one the hub picks)
429
        #[arg(long)]
430
        colour: Option<String>,
431
        #[arg(long, short, default_value = "")]
432
        description: String,
433
    },
434
    /// Delete a label, taking it off every issue and proposal (triage)
435
    Delete { name: String },
436
}
437
438
#[derive(Subcommand)]
439
enum ProjectCmd {
440
    /// The owner's boards
441
    List,
442
    /// One board: its columns and cards
443
    View {
444
        number: i64,
445
        /// Its archived cards instead (#293)
446
        #[arg(long)]
447
        archived: bool,
448
    },
449
    /// Create a board (owner, or an organisation's members)
450
    Create {
451
        title: String,
452
        #[arg(long, short, default_value = "")]
453
        description: String,
454
        /// Only the owner (or the organisation's members) can see it
455
        #[arg(long)]
456
        private: bool,
457
    },
458
    /// Close a board
459
    Close { number: i64 },
460
    /// Reopen a board
461
    Reopen { number: i64 },
462
    /// Move a board to another owner you may make boards under (an
463
    /// organisation, say); it takes the next number there
464
    Transfer {
465
        number: i64,
466
        /// The new owner
467
        #[arg(long)]
468
        to: String,
469
    },
470
    /// Cards on a board: add, move, archive, restore, remove
471
    Card {
472
        #[command(subcommand)]
473
        cmd: CardCmd,
474
    },
475
}
476
477
#[derive(Subcommand)]
478
enum CardCmd {
479
    /// Put an issue or proposal on a board (`12` or `#12` in this
480
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
481
    /// or a note with --note
482
    Add {
483
        number: i64,
484
        /// The issue or proposal; a number means this repository's
485
        reference: Option<String>,
486
        /// A note card instead
487
        #[arg(long, conflicts_with = "reference")]
488
        note: Option<String>,
489
        /// The column, by name or id (default: the first)
490
        #[arg(long, short)]
491
        column: Option<String>,
492
    },
493
    /// Move a card to another column (by name or id), or with --from every
494
    /// card of a column at once
495
    Move {
496
        number: i64,
497
        /// The card (its id); leave it out with --from
498
        card: Option<i64>,
499
        #[arg(long, short)]
500
        column: String,
501
        /// Move every card of this column (#289)
502
        #[arg(long, conflicts_with = "card")]
503
        from: Option<String>,
504
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
505
        #[arg(long, value_delimiter = ',', requires = "from")]
506
        except: Vec<String>,
507
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
508
        #[arg(long, value_delimiter = ',', requires = "from")]
509
        state: Vec<String>,
510
        /// With --from: say what would move, and move nothing
511
        #[arg(long, requires = "from")]
512
        dry_run: bool,
513
    },
514
    /// Archive a column's cards: off the board, kept and restorable (#293)
515
    Archive {
516
        number: i64,
517
        /// The column, by name or id
518
        #[arg(long)]
519
        from: String,
520
        /// Only cards that joined the column more than this long ago (14d, or 14)
521
        #[arg(long)]
522
        older: Option<String>,
523
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
524
        #[arg(long, value_delimiter = ',')]
525
        except: Vec<String>,
526
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
527
        #[arg(long, value_delimiter = ',')]
528
        state: Vec<String>,
529
        /// Say what would be archived, and archive nothing
530
        #[arg(long)]
531
        dry_run: bool,
532
    },
533
    /// Put an archived card back at the end of its column
534
    Restore { number: i64, card: i64 },
535
    /// Take a card off a board
536
    Remove { number: i64, card: i64 },
537
}
538
539
#[derive(Subcommand)]
540
enum MilestoneCmd {
541
    /// The repository's milestones
542
    List,
543
    /// Create a milestone, or change the one of that title (triage)
544
    Create {
545
        title: String,
546
        #[arg(long, short, default_value = "")]
547
        description: String,
548
        /// Due date, YYYY-MM-DD
549
        #[arg(long)]
550
        due: Option<String>,
551
    },
552
    /// Change a milestone's title, description or due date (triage)
553
    Edit {
554
        title: String,
555
        #[arg(long, short)]
556
        rename: Option<String>,
557
        #[arg(long, short)]
558
        description: Option<String>,
559
        /// Due date, YYYY-MM-DD ("" for none)
560
        #[arg(long)]
561
        due: Option<String>,
562
    },
563
    /// Close a milestone
564
    Close { title: String },
565
    /// Reopen a milestone
566
    Reopen { title: String },
567
}
568
569
/// Labels to put on or take off an issue or proposal.
570
#[derive(clap::Args)]
571
struct LabelChange {
572
    number: i64,
573
    /// A label to add (repeatable)
574
    #[arg(long, short)]
575
    add: Vec<String>,
576
    /// A label to take off (repeatable)
577
    #[arg(long, short)]
578
    remove: Vec<String>,
579
}
580
581
impl LabelChange {
582
    /// The set after the change, from the one there now.
5830×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
5840×
        if self.add.is_empty() && self.remove.is_empty() {
5850×
            bail!("say what to change: --add NAME or --remove NAME");
5860×
        }
5870×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
5880×
        for a in &self.add {
5890×
            if !names.contains(a) {
5900×
                names.push(a.clone());
5910×
            }
592
        }
5930×
        Ok(names)
5940×
    }
595
}
596
5970×
fn label_names(labels: &[String]) -> String {
5980×
    if labels.is_empty() {
5990×
        ui::dim("no labels")
600
    } else {
6010×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
602
    }
6030×
}
604
605
#[derive(Subcommand)]
606
enum CoverageCmd {
607
    /// Upload an LCOV or Cobertura report measured on this machine, as the
608
    /// coverage of a bookmark's current state (default: the default
609
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
610
    /// not measured by a runner, and sets no check from it
611
    Upload {
612
        file: std::path::PathBuf,
613
        #[arg(long)]
614
        bookmark: Option<String>,
615
        /// A change's full hash
616
        #[arg(long, conflicts_with = "bookmark")]
617
        change: Option<String>,
618
    },
619
}
620
621
#[derive(Subcommand)]
622
enum RunCmd {
623
    /// Recent runs, newest first
624
    List {
625
        #[arg(long, default_value_t = 20)]
626
        limit: i64,
627
    },
628
    /// A run and its jobs
629
    View { number: i64 },
630
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
631
    Start {
632
        #[arg(long)]
633
        bookmark: Option<String>,
634
        /// A change's full hash
635
        #[arg(long, conflicts_with = "bookmark")]
636
        change: Option<String>,
637
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
638
        #[arg(long = "job", value_name = "NAME")]
639
        jobs: Vec<String>,
640
        /// Wait for the run and exit 1 unless it passes
641
        #[arg(long)]
642
        watch: bool,
643
    },
644
    /// Follow a run until it finishes; exit 1 unless it passes
645
    Watch { number: i64 },
646
    /// A job's log
647
    Log { number: i64, job: String },
648
    /// Run a finished run's state again; with --job, only that job (and the
649
    /// jobs that depend on it) in the same run
650
    Rerun {
651
        number: i64,
652
        #[arg(long)]
653
        job: Option<String>,
654
    },
655
    /// Cancel a run still queued or running; its running jobs are stopped
656
    Cancel { number: i64 },
657
    /// Approve a job that waits for a person (oxygenflow#57)
658
    Approve {
659
        number: i64,
660
        #[arg(long)]
661
        job: String,
662
    },
663
    /// Reject a job that waits for a person: it ends cancelled
664
    Reject {
665
        number: i64,
666
        #[arg(long)]
667
        job: String,
668
    },
669
}
670
671
#[derive(Subcommand)]
672
enum TagCmd {
673
    /// Tags, newest name first
674
    List,
675
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
676
    /// delegate (as `oxy tag create` and a push would be)
677
    Create {
678
        name: String,
679
        /// What to tag (default: the default bookmark)
680
        #[arg(long)]
681
        target: Option<String>,
682
        #[arg(long, short)]
683
        message: Option<String>,
684
    },
685
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
686
    /// their next fetch, and the name is never used again. Refused while a
687
    /// release uses the tag
688
    Delete {
689
        name: String,
690
        /// Why, recorded with the withdrawal
691
        #[arg(long, short)]
692
        reason: Option<String>,
693
    },
694
}
695
696
#[derive(Subcommand)]
697
enum ReleaseCmd {
698
    /// Releases, newest first
699
    List,
700
    /// Create a release on an existing tag
701
    Create {
702
        tag: String,
703
        #[arg(long, short)]
704
        title: Option<String>,
705
        /// Notes in Markdown (default: generated from the changes since the previous release)
706
        #[arg(long, short)]
707
        notes: Option<String>,
708
        #[arg(long)]
709
        prerelease: bool,
710
    },
711
    /// Change a release's title, notes or prerelease flag
712
    Edit {
713
        tag: String,
714
        #[arg(long, short)]
715
        title: Option<String>,
716
        /// New notes in Markdown ("-" reads them from stdin)
717
        #[arg(long, short)]
718
        notes: Option<String>,
719
        /// Mark it a prerelease (true) or not (false)
720
        #[arg(long)]
721
        prerelease: Option<bool>,
722
    },
723
    /// Attach files to a release
724
    Upload { tag: String, files: Vec<std::path::PathBuf> },
725
    /// The release's trust report: signatures, builds, receipts and audit
726
    Trust { tag: String },
727
}
728
72947×
fn main() {
730
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
731
    // other command-line tools do, instead of panicking on the failed
732
    // write (oxygenhub#92).
733
    #[cfg(unix)]
73447×
    unsafe {
73547×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
73647×
    }
73747×
    let cli = Cli::parse();
73847×
    ui::init(cli.plain);
73947×
    match run(cli) {
74040×
        Ok(code) => std::process::exit(code),
7417×
        Err(e) => {
7427×
            eprintln!("{} {e:#}", ui::bad("error:"));
7437×
            std::process::exit(2);
744
        }
745
    }
746
}
747
74817×
fn enc(s: &str) -> String {
74917×
    let mut out = String::new();
75067×
    for b in s.bytes() {
75167×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
75267×
            out.push(b as char);
75367×
        } else {
7540×
            out.push_str(&format!("%{b:02X}"));
7550×
        }
756
    }
75717×
    out
75817×
}
759
76047×
fn run(cli: Cli) -> Result<i32> {
76147×
    let cfg = Config::load()?;
7621×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
7631×
        return login(cfg, url, token.clone(), ca.clone());
76446×
    }
76546×
    let here = std::env::current_dir()?;
76646×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
76745×
    let c = Client::new(&t)?;
76845×
    let json = cli.json;
7690×
    match cli.cmd {
770
        Cmd::Auth { cmd: AuthCmd::Status } => {
7710×
            let me: serde_json::Value = c.get("/user")?;
7720×
            if json {
7730×
                println!("{me}");
7740×
            } else {
7750×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
7760×
            }
7770×
            Ok(0)
778
        }
7790×
        Cmd::Auth { .. } => unreachable!(),
7801×
        Cmd::Api { path, method, data } => {
7811×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
782
            // The method applies with or without a body (#75): without one, a
783
            // GET reads, anything else sends an empty object.
7841×
            let text = match data {
7850×
                Some(d) => c.send_text(
7860×
                    &method.to_uppercase(),
7870×
                    &path,
7880×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
7890×
                )?,
7901×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
7910×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
792
            };
7931×
            println!("{text}");
7941×
            Ok(0)
795
        }
796
        Cmd::Repo { cmd: RepoCmd::View } => {
7971×
            let path = t.repo_path()?;
7981×
            if json {
7990×
                println!("{}", c.get_text(&path)?);
8000×
                return Ok(0);
8011×
            }
8021×
            let r: serde_json::Value = c.get(&path)?;
8031×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
8041×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
8051×
                println!("{d}");
8061×
            }
8071×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
8081×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
8091×
            Ok(0)
810
        }
81115×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
8124×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
8133×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
8140×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
8150×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
8160×
            let mut body = serde_json::json!({ "content": content });
8170×
            if let Some(b) = bookmark {
8180×
                body["bookmark"] = b.into();
8190×
            }
8200×
            if let Some(ch) = change {
8210×
                body["change"] = ch.into();
8220×
            }
8230×
            let base = t.repo_path()?;
8240×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
8250×
            if json {
8260×
                println!("{}", serde_json::to_string(&r)?);
827
            } else {
8280×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
8290×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
8300×
                println!(
831
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
8320×
                    ui::ok("✔"),
833
                    r.lines_hit,
834
                    r.lines_found,
835
                    r.files,
8360×
                    ui::dim(&r.url)
837
                );
8380×
                if r.dropped > 0 {
8390×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
8400×
                }
841
            }
8420×
            Ok(0)
843
        }
8444×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
8450×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
8460×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
8470×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
84810×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
8490×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
8500×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
8517×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
852
    }
85347×
}
854
855
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
8567×
fn drop_id(s: &str) -> Result<String> {
8577×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
858144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
8591×
        bail!("{s:?} is not a drop's id or address");
8606×
    }
8616×
    Ok(id.to_ascii_lowercase())
8627×
}
863
8642×
fn drop_line(d: &hub_api::Drop) -> String {
8652×
    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() };
8664×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
8672×
    format!(
868
        "{} {} {}{}",
8692×
        ui::dim(&d.id),
8702×
        ui::strong(&title),
8712×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
8722×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
873
    )
8742×
}
875
8767×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
8777×
    match cmd {
8781×
        DropCmd::Create { files, secret, description, title } => {
8791×
            let mut out = Vec::with_capacity(files.len());
8802×
            for f in &files {
8812×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
8822×
                let content =
8832×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
8842×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
885
            }
8861×
            let new =
8871×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
8881×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
8891×
            if json {
8901×
                println!("{}", serde_json::to_string(&d)?);
891
            } else {
8920×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
8930×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
894
            }
895
        }
8962×
        DropCmd::List { user } => {
8972×
            let path = match &user {
8981×
                Some(u) => format!("/users/{}/drops", enc(u)),
8991×
                None => "/drops".to_string(),
900
            };
9012×
            if json {
9021×
                println!("{}", c.get_text(&path)?);
9031×
                return Ok(0);
9041×
            }
9051×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
9061×
            if list.is_empty() {
9070×
                println!("{}", ui::dim("No drops."));
9081×
            }
9091×
            for d in &list {
9101×
                println!("{}", drop_line(d));
9111×
            }
912
        }
9133×
        DropCmd::View { id, file } => {
9143×
            let path = format!("/drops/{}", drop_id(&id)?);
9153×
            if json && file.is_none() {
9160×
                println!("{}", c.get_text(&path)?);
9170×
                return Ok(0);
9183×
            }
9193×
            let d: hub_api::Drop = c.get(&path)?;
9202×
            if let Some(name) = file {
9212×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
9221×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
9231×
                print!("{content}");
9241×
                return Ok(0);
9251×
            }
9261×
            println!("{}", drop_line(&d));
9271×
            if !d.description.is_empty() {
9281×
                println!("{}", d.description);
9291×
            }
9301×
            println!("{}", ui::kv("url", &d.url));
9311×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
9322×
            for f in &d.files {
9332×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
9342×
                match &f.content {
9352×
                    Some(text) => {
9362×
                        print!("{text}");
9372×
                        if !text.ends_with('\n') && !text.is_empty() {
9380×
                            println!();
9392×
                        }
940
                    }
9410×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
942
                }
943
            }
944
        }
9451×
        DropCmd::Delete { id } => {
9461×
            let id = drop_id(&id)?;
9471×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
9481×
            println!("{} drop {id}", ui::ok("✔ deleted"));
949
        }
950
    }
9514×
    Ok(0)
9527×
}
953
954
/// `30d`, `12h`, `90m` in milliseconds.
9550×
fn duration_ms(s: &str) -> Result<i64> {
9560×
    let s = s.trim();
9570×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
9580×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
9590×
    let per = match unit {
9600×
        "d" => 86_400_000,
9610×
        "h" => 3_600_000,
9620×
        "m" => 60_000,
9630×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
964
    };
9650×
    if n <= 0 {
9660×
        bail!("a grant must last some time");
9670×
    }
9680×
    Ok(n * per)
9690×
}
970
9710×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
972
    use oxy_core::cert::{Grant, SignedGrant};
973
    use oxy_core::identity::{Identity, Scope};
9740×
    match cmd {
9750×
        AgentCmd::Grant { name, scope, lasts } => {
9760×
            let home = oxy_core::repo::default_home();
9770×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
9780×
                format!(
979
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
9800×
                    home.display()
981
                )
9820×
            })?;
9830×
            let me: serde_json::Value = c.get("/user")?;
9840×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
9850×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
9860×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
9870×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
9880×
            let grant = Grant {
9890×
                grantor: me_id.hash(),
9900×
                subject: format!("agent:{name}@{username}"),
9910×
                issuer: hub.hash(),
9920×
                scope,
9930×
                not_before: (now - 60_000) as u64,
9940×
                expires: (now + duration_ms(&lasts)?) as u64,
995
            };
9960×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
9970×
            let r: serde_json::Value =
9980×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
9990×
            if json {
10000×
                println!("{r}");
10010×
                return Ok(0);
10020×
            }
10030×
            println!(
1004
                "{} {} to act for you as {} ({}), until {}",
10050×
                ui::ok("✔ granted"),
10060×
                ui::strong(&name),
10070×
                r["subject"].as_str().unwrap_or(""),
10080×
                r["scope"].as_str().unwrap_or(""),
10090×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1010
            );
10110×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
10120×
            println!(
1013
                "  {}",
10140×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1015
            );
10160×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
10170×
            Ok(0)
1018
        }
1019
        AgentCmd::List => {
10200×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
10210×
            if json {
10220×
                println!("{}", serde_json::to_string(&grants)?);
10230×
                return Ok(0);
10240×
            }
10250×
            if grants.is_empty() {
10260×
                println!("{}", ui::dim("no agent grants"));
10270×
            }
10280×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
10290×
            for g in grants {
10300×
                let state = if g["revoked_ms"].is_i64() {
10310×
                    ui::bad("revoked")
10320×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
10330×
                    ui::dim("ended")
1034
                } else {
10350×
                    ui::ok("live")
1036
                };
10370×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
10380×
                println!(
1039
                    "#{:<4} {:<8} {} · {} · until {} · {}",
10400×
                    g["id"],
1041
                    state,
10420×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
10430×
                    g["scope"].as_str().unwrap_or(""),
10440×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
10450×
                    ui::dim(&used)
1046
                );
1047
            }
10480×
            Ok(0)
1049
        }
10500×
        AgentCmd::Revoke { id } => {
10510×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
10520×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
10530×
            Ok(0)
1054
        }
1055
    }
10560×
}
1057
10581×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
10591×
    let hub = url.trim_end_matches('/').to_string();
10601×
    let token = match token.as_deref() {
10611×
        Some("-") => {
10620×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
10630×
            let mut line = String::new();
10640×
            std::io::stdin().read_line(&mut line)?;
10650×
            line.trim().to_string()
1066
        }
10671×
        Some(t) => t.to_string(),
10680×
        None => device_sign_in(&hub, ca.clone())?,
1069
    };
10701×
    if token.is_empty() {
10710×
        bail!("no token given");
10721×
    }
10731×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
10741×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
10751×
    let account = me["username"].as_str().unwrap_or("?");
1076
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
10771×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
10781×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
10791×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
10801×
    cfg.default_hub = Some(hub.clone());
10811×
    cfg.save()?;
10821×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
10831×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
10841×
    Ok(0)
10851×
}
1086
1087
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1088
/// it on the web, and the token arrives here.
10890×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
10900×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
10910×
    let c = Client::new(&t)?;
10920×
    let host = std::fs::read_to_string("/etc/hostname")
10930×
        .ok()
10940×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
10950×
        .map(|h| h.trim().to_string())
10960×
        .filter(|h| !h.is_empty());
10970×
    let client = match host {
10980×
        Some(h) => format!("oh on {h}"),
10990×
        None => "oh".to_string(),
1100
    };
11010×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
11020×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
11030×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
11040×
    if code != 200 {
11050×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
11060×
    }
11070×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
11080×
    let user = v["user_code"].as_str().unwrap_or("?");
11090×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
11100×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
11110×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
11120×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
11130×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1114
    loop {
11150×
        std::thread::sleep(std::time::Duration::from_secs(interval));
11160×
        if std::time::Instant::now() > deadline {
11170×
            bail!("the code expired before it was approved; run oh auth login again");
11180×
        }
11190×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
11200×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
11210×
        if code == 200 {
11220×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
11230×
        }
11240×
        match v["error"].as_str() {
11250×
            Some("authorization_pending") => {}
11260×
            Some("slow_down") => interval += 5,
11270×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
11280×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
11290×
            _ => bail!("signing in: HTTP {code}: {body}"),
1130
        }
1131
    }
11320×
}
1133
11347×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
11357×
    match (body, file) {
11362×
        (Some(b), _) => Ok(b),
11371×
        (None, Some(f)) if f == "-" => {
11380×
            let mut s = String::new();
11390×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
11400×
            Ok(s)
1141
        }
11421×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
11434×
        (None, None) => Ok(String::new()),
1144
    }
11457×
}
1146
11473×
fn issue_line(i: &Issue) -> String {
11483×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
11493×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
11503×
    format!(
1151
        "{glyph} {} {}{}{}",
11523×
        ui::dim(&format!("#{}", i.number)),
1153
        i.title,
11543×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
11553×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1156
    )
11573×
}
1158
115915×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
116015×
    let base = t.repo_path()?;
116115×
    match cmd {
11623×
        IssueCmd::List { state } => {
11633×
            let path = format!("{base}/issues?state={}", enc(&state));
11643×
            if json {
11651×
                println!("{}", c.get_text(&path)?);
11661×
                return Ok(0);
11672×
            }
11682×
            let list: Vec<Issue> = c.get(&path)?;
11692×
            if list.is_empty() {
11701×
                println!("{}", ui::dim(&format!("No {state} issues.")));
11711×
            }
11722×
            for i in &list {
11732×
                println!("{}", issue_line(i));
11742×
            }
1175
        }
11762×
        IssueCmd::View { number } => {
11772×
            let path = format!("{base}/issues/{number}");
11782×
            if json {
11791×
                println!("{}", c.get_text(&path)?);
11801×
                return Ok(0);
11811×
            }
11821×
            let i: Issue = c.get(&path)?;
11831×
            println!("{}", issue_line(&i));
11841×
            if !i.body.trim().is_empty() {
11851×
                println!("\n{}\n", i.body.trim_end());
11861×
            }
11871×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
11882×
            for cm in comments {
11892×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
11902×
            }
11911×
            println!("{}", ui::dim(&i.url));
1192
        }
11933×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
11943×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
11953×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
11962×
            if json {
11970×
                println!("{}", serde_json::to_string(&i)?);
11982×
            } else {
11992×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
12002×
            }
12012×
            if let Some(n) = project {
12021×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
12031×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
12041×
                if !json {
12051×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
12061×
                }
12071×
            }
1208
        }
12091×
        IssueCmd::Close { number, reason } => {
12101×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
12111×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1212
        }
12130×
        IssueCmd::Reopen { number } => {
12140×
            let i: Issue =
12150×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
12160×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1217
        }
12183×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
12193×
            let body = match (&body, &body_file) {
12203×
                (None, None) => None,
12210×
                _ => Some(body_of(body, body_file)?),
1222
            };
12233×
            let labels = if no_labels {
12241×
                Some(Vec::new())
12252×
            } else if label.is_empty() {
12261×
                None
1227
            } else {
12281×
                Some(label)
1229
            };
12303×
            let assignees = if no_assignees {
12311×
                Some(Vec::new())
12322×
            } else if assignee.is_empty() {
12331×
                None
1234
            } else {
12351×
                Some(assignee)
1236
            };
12373×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
12381×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
12392×
            }
12402×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
12412×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
12422×
            if json {
12431×
                println!("{}", serde_json::to_string(&i)?);
12441×
            } else {
12451×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
12461×
            }
1247
        }
12480×
        IssueCmd::Label(change) => {
12490×
            let path = format!("{base}/issues/{}", change.number);
12500×
            let now: Issue = c.get(&path)?;
12510×
            let labels = change.apply(&now.labels)?;
12520×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
12530×
            let i: Issue = c.send("PATCH", &path, &edit)?;
12540×
            if json {
12550×
                println!("{}", serde_json::to_string(&i)?);
12560×
            } else {
12570×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
12580×
            }
1259
        }
12603×
        IssueCmd::Comment { number, body, body_file } => {
12613×
            let body = body_of(body, body_file)?;
12623×
            if body.trim().is_empty() {
12631×
                bail!("give the comment with --body or --body-file");
12642×
            }
12652×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
12662×
            println!("{} commented on #{number}", ui::ok("✔"));
1267
        }
1268
    }
126910×
    Ok(0)
127015×
}
1271
12721×
fn source_name(s: &hub_api::ProposalSource) -> String {
12731×
    match s {
12741×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
12750×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
12760×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1277
    }
12781×
}
1279
12801×
fn proposal_line(p: &Proposal) -> String {
12811×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
12821×
    let glyph = match state.as_str() {
12831×
        "open" => ui::ok("●"),
12840×
        "draft" => ui::dim("◌"),
12850×
        "landed" => ui::strong("✔"),
12860×
        _ => ui::dim("○"),
1287
    };
12881×
    format!(
1289
        "{glyph} {} {} {}{}",
12901×
        ui::dim(&format!("#{}", p.number)),
1291
        p.title,
12921×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
12931×
        ui::dim(&format!(" · {} · {state}", p.author))
1294
    )
12951×
}
1296
12974×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
12984×
    let base = t.repo_path()?;
12994×
    match cmd {
13000×
        ProposalCmd::List { state } => {
13010×
            let path = format!("{base}/proposals?state={state}");
13020×
            if json {
13030×
                println!("{}", c.get_text(&path)?);
13040×
                return Ok(0);
13050×
            }
13060×
            let list: Vec<Proposal> = c.get(&path)?;
13070×
            if list.is_empty() {
13080×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
13090×
            }
13100×
            for p in &list {
13110×
                println!("{}", proposal_line(p));
13120×
            }
1313
        }
13141×
        ProposalCmd::View { number } => {
13151×
            let path = format!("{base}/proposals/{number}");
13161×
            if json {
13170×
                println!("{}", c.get_text(&path)?);
13180×
                return Ok(0);
13191×
            }
13201×
            let p: Proposal = c.get(&path)?;
13211×
            println!("{}", proposal_line(&p));
13221×
            if !p.body.trim().is_empty() {
13230×
                println!("\n{}\n", p.body.trim_end());
13241×
            }
13251×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
13261×
            for ch in &p.changes {
13271×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
13281×
            }
13291×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
13301×
            if p.landable {
13311×
                println!("{} can land", ui::ok("✔"));
13321×
            } else {
13330×
                for b in &p.blockers {
13340×
                    println!("{} {b}", ui::bad("✘"));
13350×
                }
1336
            }
13371×
            if p.conflicted {
13380×
                println!("{} landing it would leave conflicts", ui::bad("!"));
13391×
            }
13401×
            println!("{}", ui::dim(&p.url));
1341
        }
13421×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
13431×
            let target = match into {
13440×
                Some(i) => i,
13451×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1346
            };
13471×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
13481×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
13491×
            if json {
13500×
                println!("{}", serde_json::to_string(&p)?);
13511×
            } else {
13521×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
13531×
            }
1354
        }
13550×
        ProposalCmd::Edit { number, title, body, body_file } => {
13560×
            let body = match (&body, &body_file) {
13570×
                (None, None) => None,
13580×
                _ => Some(body_of(body, body_file)?),
1359
            };
13600×
            if title.is_none() && body.is_none() {
13610×
                bail!("say what to change: --title, --body or --body-file");
13620×
            }
13630×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
13640×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
13650×
            if json {
13660×
                println!("{}", serde_json::to_string(&p)?);
13670×
            } else {
13680×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
13690×
            }
1370
        }
13710×
        ProposalCmd::Label(change) => {
13720×
            let path = format!("{base}/proposals/{}", change.number);
13730×
            let now: Proposal = c.get(&path)?;
13740×
            let labels = change.apply(&now.labels)?;
13750×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
13760×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
13770×
            if json {
13780×
                println!("{}", serde_json::to_string(&p)?);
13790×
            } else {
13800×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
13810×
            }
1382
        }
13830×
        ProposalCmd::Comment { number, body, body_file } => {
13840×
            let body = body_of(body, body_file)?;
13850×
            if body.trim().is_empty() {
13860×
                bail!("give the comment with --body or --body-file");
13870×
            }
13880×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
13890×
            println!("{} commented on #{number}", ui::ok("✔"));
1390
        }
13910×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
13920×
            let path = format!("{base}/proposals/{number}/auto-land");
13930×
            let p: Proposal =
13940×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
13950×
            if json {
13960×
                println!("{}", serde_json::to_string(&p)?);
13970×
            } else if p.landed.is_some() {
13980×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
13990×
            } else if p.auto_land.is_some() {
14000×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
14010×
            } else {
14020×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
14030×
            }
1404
        }
14052×
        ProposalCmd::Land { number, over_checks, .. } => {
14062×
            let body = match &over_checks {
14070×
                Some(r) => serde_json::json!({ "over_checks": r }),
14082×
                None => serde_json::json!({}),
1409
            };
14102×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
14111×
            if json {
14120×
                println!("{}", serde_json::to_string(&p)?);
14131×
            } else {
14141×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
14151×
            }
1416
        }
14170×
        ProposalCmd::Close { number, message } => {
14180×
            if let Some(body) = message {
14190×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
14200×
            }
14210×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
14220×
            if json {
14230×
                println!("{}", serde_json::to_string(&p)?);
14240×
            } else {
14250×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
14260×
            }
1427
        }
14280×
        ProposalCmd::Reopen { number } => {
14290×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
14300×
            if json {
14310×
                println!("{}", serde_json::to_string(&p)?);
14320×
            } else {
14330×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
14340×
            }
1435
        }
14360×
        ProposalCmd::Ready { number, undo } => {
14370×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
14380×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
14390×
            if json {
14400×
                println!("{}", serde_json::to_string(&p)?);
14410×
            } else if undo {
14420×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
14430×
            } else {
14440×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
14450×
            }
1446
        }
14470×
        ProposalCmd::Checks { number } => {
14480×
            let path = format!("{base}/proposals/{number}/checks");
14490×
            if json {
14500×
                println!("{}", c.get_text(&path)?);
14510×
                return Ok(0);
14520×
            }
14530×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
14540×
            if checks.is_empty() {
14550×
                println!("{}", ui::dim("No checks yet."));
14560×
            }
14570×
            for ch in checks {
14580×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
14590×
            }
1460
        }
1461
    }
14623×
    Ok(0)
14634×
}
1464
14651×
fn run_line(r: &FlowRun) -> String {
14661×
    let what =
14671×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
14681×
    format!(
1469
        "{} {} {} {}",
14701×
        ui::status(&r.status),
14711×
        ui::dim(&format!("#{}", r.number)),
1472
        what,
14731×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1474
    )
14751×
}
1476
14771×
fn print_run(r: &FlowRun) {
14781×
    println!("{}", run_line(r));
14791×
    for j in &r.jobs {
14801×
        let dur = match (j.started_ms, j.finished_ms) {
14810×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
14821×
            _ => String::new(),
1483
        };
14841×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
14851×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1486
        // Why a queued job no runner can take waits (oxygenhub#28), and
1487
        // why a job ran where it did (oxygenflow#42).
14881×
        if j.status == "queued" && !j.waiting.is_empty() {
14890×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
14901×
        } else if !j.placed.is_empty() {
14910×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
14921×
        }
1493
    }
14941×
    if !r.error.is_empty() {
14950×
        println!("{}", ui::bad(&r.error));
14961×
    }
14971×
    println!("{}", ui::dim(&r.url));
14981×
}
1499
15000×
fn live(status: &str) -> bool {
15010×
    matches!(status, "queued" | "running")
15020×
}
1503
1504
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
15050×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
15060×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
15070×
    if json {
15080×
        println!("{done}");
15090×
    } else {
15100×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
15110×
    }
15120×
    Ok(())
15130×
}
1514
15150×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
15160×
    let path = format!("{base}/flow/runs/{number}");
15170×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1518
    loop {
15190×
        let r: FlowRun = c.get(&path)?;
15200×
        if !json {
15210×
            for j in &r.jobs {
15220×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
15230×
                if seen.get(&j.name) != Some(&shown) {
15240×
                    println!("{} {}", ui::status(&j.status), j.name);
15250×
                    if j.status == "queued" && !j.waiting.is_empty() {
15260×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
15270×
                    }
15280×
                    seen.insert(j.name.clone(), shown);
15290×
                }
1530
            }
15310×
        }
15320×
        if !live(&r.status) {
15330×
            if json {
15340×
                println!("{}", serde_json::to_string(&r)?);
15350×
            } else {
15360×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
15370×
            }
15380×
            return Ok(if r.status == "passed" { 0 } else { 1 });
15390×
        }
15400×
        std::thread::sleep(Duration::from_secs(3));
1541
    }
15420×
}
1543
15443×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
15453×
    let base = t.repo_path()?;
15460×
    match cmd {
15471×
        RunCmd::List { limit } => {
15481×
            let path = format!("{base}/flow/runs?limit={limit}");
15491×
            if json {
15501×
                println!("{}", c.get_text(&path)?);
15511×
                return Ok(0);
15520×
            }
15530×
            let runs: Vec<FlowRun> = c.get(&path)?;
15540×
            if runs.is_empty() {
15550×
                println!("{}", ui::dim("No runs yet."));
15560×
            }
15570×
            for r in &runs {
15580×
                println!("{}", run_line(r));
15590×
            }
1560
        }
15611×
        RunCmd::View { number } => {
15621×
            let path = format!("{base}/flow/runs/{number}");
15631×
            if json {
15640×
                println!("{}", c.get_text(&path)?);
15650×
                return Ok(0);
15661×
            }
15671×
            print_run(&c.get(&path)?);
1568
        }
15691×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
15701×
            let mut body = match (bookmark, change) {
15710×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
15720×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
15731×
                (None, None) => serde_json::json!({}),
1574
            };
15751×
            if !jobs.is_empty() {
15760×
                body["jobs"] = serde_json::json!(jobs);
15771×
            }
15781×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
15791×
            let n = started["number"].as_i64().context("the hub named no run")?;
15801×
            if !json || !follow {
15811×
                if json {
15820×
                    println!("{started}");
15831×
                } else {
15841×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
15851×
                }
15860×
            }
15871×
            if follow {
15880×
                return watch(c, &base, n, json);
15891×
            }
1590
        }
15910×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
15920×
        RunCmd::Log { number, job } => {
15930×
            let mut after = 0;
1594
            loop {
15950×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
15960×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
15970×
                if lines.is_empty() {
15980×
                    break;
15990×
                }
16000×
                for l in &lines {
16010×
                    if json {
16020×
                        println!("{}", serde_json::to_string(l)?);
16030×
                    } else if l.stream == "flow" {
16040×
                        println!("{}", ui::dim(&l.text));
16050×
                    } else {
16060×
                        println!("{}", l.text);
16070×
                    }
1608
                }
16090×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1610
            }
1611
        }
16120×
        RunCmd::Rerun { number, job: Some(job) } => {
16130×
            let queued: serde_json::Value =
16140×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
16150×
            if json {
16160×
                println!("{queued}");
16170×
            } else {
16180×
                let n = queued["queued"].as_i64().unwrap_or(1);
16190×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
16200×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1621
            }
1622
        }
16230×
        RunCmd::Rerun { number, job: None } => {
16240×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
16250×
            if json {
16260×
                println!("{started}");
16270×
            } else {
16280×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
16290×
            }
1630
        }
16310×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
16320×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
16330×
        RunCmd::Cancel { number } => {
16340×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
16350×
            if json {
16360×
                println!("{done}");
16370×
            } else {
16380×
                println!("{} cancelled run #{number}", ui::ok("✔"));
16390×
            }
1640
        }
1641
    }
16422×
    Ok(0)
16433×
}
1644
16450×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
16460×
    let base = t.repo_path()?;
16470×
    match cmd {
1648
        LabelCmd::List => {
16490×
            let path = format!("{base}/labels");
16500×
            if json {
16510×
                println!("{}", c.get_text(&path)?);
16520×
                return Ok(0);
16530×
            }
16540×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
16550×
            if labels.is_empty() {
16560×
                println!("{}", ui::dim("No labels."));
16570×
            }
16580×
            for l in labels {
16590×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
16600×
            }
1661
        }
16620×
        LabelCmd::Create { name, colour, description } => {
16630×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
16640×
            if json {
16650×
                println!("{}", serde_json::to_string(&l)?);
16660×
            } else {
16670×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
16680×
            }
1669
        }
16700×
        LabelCmd::Delete { name } => {
16710×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
16720×
            println!("{} deleted label {name}", ui::ok("✔"));
1673
        }
1674
    }
16750×
    Ok(0)
16760×
}
1677
16780×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
16790×
    let base = match (&org, site) {
16800×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
16810×
        (None, true) => "/admin/assistants".to_string(),
16820×
        (None, false) => format!("{}/assistants", t.repo_path()?),
1683
    };
16840×
    match cmd {
1685
        AssistantCmd::List => {
16860×
            if json {
16870×
                println!("{}", c.get_text(&base)?);
16880×
                return Ok(0);
16890×
            }
16900×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
16910×
            if list.is_empty() {
16920×
                println!("{}", ui::dim("No assistants."));
16930×
            }
16940×
            for a in list {
16950×
                let state = if a.enabled && !a.off_above {
16960×
                    ui::ok("on")
16970×
                } else if a.off_above {
16980×
                    ui::dim("off above")
1699
                } else {
17000×
                    ui::dim("off")
1701
                };
17020×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
17030×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1704
            }
1705
        }
17060×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
17070×
            let token = match token_env {
17080×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
17090×
                None => String::new(),
1710
            };
17110×
            let body =
17120×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
17130×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
17140×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1715
        }
17160×
        AssistantCmd::Remove { name } => {
17170×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
17180×
            println!("{} removed {name}", ui::ok("✔"));
1719
        }
17200×
        AssistantCmd::Prompt { set } => {
17210×
            let p: hub_api::AssistantPrompt = match set {
17220×
                Some(path) => {
17230×
                    let text = if path.as_os_str() == "-" {
17240×
                        let mut s = String::new();
17250×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
17260×
                        s
1727
                    } else {
17280×
                        std::fs::read_to_string(&path)?
1729
                    };
17300×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1731
                }
17320×
                None => c.get(&format!("{base}/prompt"))?,
1733
            };
17340×
            if json {
17350×
                println!("{}", serde_json::to_string(&p)?);
17360×
                return Ok(0);
17370×
            }
17380×
            for (from, text) in &p.inherited {
17390×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
17400×
            }
17410×
            if p.prompt.is_empty() {
17420×
                println!("{}", ui::dim("No prompt of its own."));
17430×
            } else {
17440×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
17450×
            }
1746
        }
1747
    }
17480×
    Ok(0)
17490×
}
1750
17512×
fn project_line(p: &hub_api::Project) -> String {
17522×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
17532×
    let private = if p.public { "" } else { " · private" };
17542×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
17552×
}
1756
175710×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
175810×
    let owner = match owner {
17590×
        Some(o) => o,
176010×
        None => t.repo()?.0.to_string(),
1761
    };
176210×
    let base = format!("/projects/{}", enc(&owner));
176310×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
17641×
        let p: hub_api::Project =
17651×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
17661×
        if json {
17670×
            println!("{}", serde_json::to_string(&p)?);
17681×
        } else {
17691×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
17701×
        }
17711×
        Ok(())
17721×
    };
17734×
    match cmd {
1774
        ProjectCmd::List => {
17751×
            if json {
17760×
                println!("{}", c.get_text(&base)?);
17770×
                return Ok(0);
17781×
            }
17791×
            let list: Vec<hub_api::Project> = c.get(&base)?;
17801×
            if list.is_empty() {
17810×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
17821×
            }
17831×
            for p in &list {
17841×
                println!("{}", project_line(p));
17851×
            }
1786
        }
17873×
        ProjectCmd::View { number, archived } => {
17883×
            let path = format!("{base}/{number}");
17893×
            let cards = format!("{path}/cards?archived=true");
17903×
            if json {
17912×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
17922×
                return Ok(0);
17931×
            }
17941×
            let mut b: hub_api::Board = c.get(&path)?;
17951×
            if archived {
17960×
                b.columns = c.get(&cards)?;
17971×
            }
17981×
            println!("{}", project_line(&b.project));
17991×
            if !b.project.description.is_empty() {
18001×
                println!("{}", b.project.description);
18011×
            }
18023×
            for col in &b.columns {
18033×
                println!();
18043×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
18053×
                if col.cards.is_empty() {
18061×
                    println!("  {}", ui::dim("(empty)"));
18072×
                }
18083×
                for card in &col.cards {
18092×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
18102×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
18112×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
18122×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
18132×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
18142×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
1815
                }
1816
            }
18171×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1818
        }
18191×
        ProjectCmd::Create { title, description, private } => {
18201×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
18211×
            if json {
18220×
                println!("{}", serde_json::to_string(&p)?);
18231×
            } else {
18241×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
18251×
            }
1826
        }
18271×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
18280×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
18290×
        ProjectCmd::Transfer { number, to } => {
18300×
            let p: hub_api::Project =
18310×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
18320×
            if json {
18330×
                println!("{}", serde_json::to_string(&p)?);
18340×
            } else {
18350×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
18360×
            }
1837
        }
18382×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1839
            // The hub names a card's issue as `repo#N` among the owner's
1840
            // repositories.
18412×
            let reference = match reference {
18421×
                None => String::new(),
18431×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
18440×
                    Some((o, rest)) if o == owner => rest.to_string(),
18450×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
18460×
                    None => r,
1847
                },
18481×
                Some(r) => {
18491×
                    let n = r.trim_start_matches('#');
18501×
                    if n.parse::<i64>().is_err() {
18510×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
18521×
                    }
18531×
                    format!("{}#{n}", t.repo()?.1)
1854
                }
1855
            };
18562×
            let note = note.unwrap_or_default();
18572×
            if reference.is_empty() && note.is_empty() {
18580×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
18592×
            }
18601×
            let card: hub_api::ProjectCard =
18612×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
18621×
            if json {
18630×
                println!("{}", serde_json::to_string(&card)?);
1864
            } else {
18651×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
1866
            }
1867
        }
18681×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
18691×
            (Some(card), None) => {
18701×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
18711×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
1872
            }
18730×
            (None, Some(from)) => {
18740×
                let r: hub_api::CardsMoved = c.send(
18750×
                    "POST",
18760×
                    &format!("{base}/{number}/cards/move"),
18770×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
18780×
                )?;
18790×
                if json {
18800×
                    println!("{}", serde_json::to_string(&r)?);
18810×
                    return Ok(0);
18820×
                }
18830×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
18840×
                for m in &r.moved {
18850×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
1886
                }
18870×
                let verb = if dry_run { "would move" } else { "moved" };
18880×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
1889
            }
18900×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
1891
        },
18920×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
18930×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
18940×
                None => None,
18950×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
1896
            };
18970×
            let r: hub_api::CardsArchived = c.send(
18980×
                "POST",
18990×
                &format!("{base}/{number}/cards/archive"),
19000×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
19010×
            )?;
19020×
            if json {
19030×
                println!("{}", serde_json::to_string(&r)?);
19040×
                return Ok(0);
19050×
            }
19060×
            let verb = if dry_run { "would archive" } else { "archived" };
19070×
            for a in &r.archived {
19080×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
19090×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
1910
            }
19110×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
1912
        }
19130×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
19140×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
19150×
            println!("{} card {card} restored", ui::ok("✔"));
1916
        }
19171×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
19181×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
19191×
            println!("{} card {card} removed", ui::ok("✔"));
1920
        }
1921
    }
19227×
    Ok(0)
192310×
}
1924
19250×
fn milestone_line(m: &hub_api::Milestone) -> String {
19260×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
19270×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
19280×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
19290×
}
1930
19310×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
19320×
    let base = t.repo_path()?;
19330×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
19340×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
19350×
        if json {
19360×
            println!("{}", serde_json::to_string(&m)?);
19370×
        } else {
19380×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
19390×
        }
19400×
        Ok(())
19410×
    };
19420×
    match cmd {
1943
        MilestoneCmd::List => {
19440×
            let path = format!("{base}/milestones");
19450×
            if json {
19460×
                println!("{}", c.get_text(&path)?);
19470×
                return Ok(0);
19480×
            }
19490×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
19500×
            if list.is_empty() {
19510×
                println!("{}", ui::dim("No milestones."));
19520×
            }
19530×
            for m in &list {
19540×
                println!("{}", milestone_line(m));
19550×
            }
1956
        }
19570×
        MilestoneCmd::Create { title, description, due } => {
19580×
            let m: hub_api::Milestone =
19590×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
19600×
            if json {
19610×
                println!("{}", serde_json::to_string(&m)?);
19620×
            } else {
19630×
                println!("{} milestone {}", ui::ok("✔"), m.title);
19640×
            }
1965
        }
19660×
        MilestoneCmd::Edit { title, rename, description, due } => {
19670×
            if rename.is_none() && description.is_none() && due.is_none() {
19680×
                bail!("say what to change: --rename, --description or --due");
19690×
            }
19700×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1971
        }
19720×
        MilestoneCmd::Close { title } => {
19730×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1974
        }
19750×
        MilestoneCmd::Reopen { title } => {
19760×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
1977
        }
1978
    }
19790×
    Ok(0)
19800×
}
1981
19820×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
19830×
    let base = t.repo_path()?;
19840×
    match cmd {
1985
        TagCmd::List => {
19860×
            let path = format!("{base}/tags");
19870×
            if json {
19880×
                println!("{}", c.get_text(&path)?);
19890×
                return Ok(0);
19900×
            }
19910×
            let tags: Vec<Tag> = c.get(&path)?;
19920×
            if tags.is_empty() {
19930×
                println!("{}", ui::dim("no tags"));
19940×
            }
19950×
            for t in tags {
19960×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
19970×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
19980×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
1999
            }
2000
        }
20010×
        TagCmd::Create { name, target, message } => {
20020×
            let new = hub_api::NewTag { name, target, message };
20030×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
20040×
            if json {
20050×
                println!("{}", serde_json::to_string(&made)?);
20060×
            } else {
20070×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
20080×
            }
2009
        }
20100×
        TagCmd::Delete { name, reason } => {
20110×
            let reason = reason.unwrap_or_default();
20120×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
20130×
            if json {
20140×
                println!("{}", serde_json::json!({ "withdrawn": name }));
20150×
            } else {
20160×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
20170×
            }
2018
        }
2019
    }
20200×
    Ok(0)
20210×
}
2022
20234×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
20244×
    let base = t.repo_path()?;
20254×
    match cmd {
2026
        ReleaseCmd::List => {
20271×
            let path = format!("{base}/releases");
20281×
            if json {
20291×
                println!("{}", c.get_text(&path)?);
20301×
                return Ok(0);
20310×
            }
20320×
            let list: Vec<Release> = c.get(&path)?;
20330×
            if list.is_empty() {
20340×
                println!("{}", ui::dim("No releases."));
20350×
            }
20360×
            for r in &list {
20370×
                println!(
2038
                    "{} {} {}{}",
20390×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
20400×
                    ui::strong(&r.tag),
2041
                    r.title,
20420×
                    ui::dim(&format!(
2043
                        " · {} asset{} · {}",
20440×
                        r.assets.len(),
20450×
                        if r.assets.len() == 1 { "" } else { "s" },
20460×
                        ui::ago(r.created_ms)
2047
                    ))
2048
                );
2049
            }
2050
        }
20511×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
20521×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
20531×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
20541×
            if json {
20550×
                println!("{}", serde_json::to_string(&r)?);
20561×
            } else {
20571×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
20581×
            }
2059
        }
20600×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
20610×
            let notes = match notes.as_deref() {
20620×
                Some("-") => Some(body_of(None, Some("-".into()))?),
20630×
                _ => notes,
2064
            };
20650×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
20660×
                bail!("say what to change: --title, --notes or --prerelease");
20670×
            }
20680×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
20690×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
20700×
            if json {
20710×
                println!("{}", serde_json::to_string(&r)?);
20720×
            } else {
20730×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
20740×
            }
2075
        }
20761×
        ReleaseCmd::Upload { tag, files } => {
20771×
            if files.is_empty() {
20780×
                bail!("name the files to attach");
20791×
            }
20801×
            for f in files {
20811×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
20821×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
20831×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
20841×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2085
            }
2086
        }
20871×
        ReleaseCmd::Trust { tag } => {
20881×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
20891×
            if json {
20900×
                println!("{}", c.get_text(&path)?);
20910×
                return Ok(0);
20921×
            }
20931×
            let r: serde_json::Value = c.get(&path)?;
20941×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
20951×
            let mut worst = 0;
20964×
            for ch in r["audit"].as_array().into_iter().flatten() {
20974×
                let v = ch["verdict"].as_str().unwrap_or("");
20984×
                worst = worst.max(match v {
20994×
                    "fail" => 2,
21004×
                    "warn" => 1,
21013×
                    _ => 0,
2102
                });
21034×
                let g = match v {
21044×
                    "pass" => ui::ok("✔"),
21051×
                    "warn" => ui::warn("!"),
21060×
                    _ => ui::bad("✘"),
2107
                };
21084×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2109
            }
21101×
            return Ok(if worst == 2 { 1 } else { 0 });
2111
        }
2112
    }
21132×
    Ok(0)
21144×
}
2115
2116
#[cfg(test)]
2117
mod tests {
2118
    use super::*;
2119
2120
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2121
    /// help says, and a drop is named by its id or its address.
2122
    #[test]
21231×
    fn drop_commands_parse() {
21241×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
21251×
        match cli.cmd {
21261×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
21271×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
21281×
                assert!(secret);
21291×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2130
            }
21310×
            _ => panic!("not drop create"),
2132
        }
21331×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
21341×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
21351×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
21360×
            _ => panic!("not drop list"),
2137
        }
21381×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
21391×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
21401×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2141
            }
21420×
            _ => panic!("not drop view"),
2143
        }
21441×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
21451×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
21461×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
21471×
        assert!(drop_id("andy/notes").is_err());
21481×
    }
2149
}