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