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