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