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