OXYGENHUB
# 0e04dfc20211 oxygenhub / crates / oh / src / main.rs
60.6 KiB · Rust · last changed Close and reopen a proposal through the API and oh 23 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};
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 and releases")]
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
    /// The repository's labels
76
    Label {
77
        #[command(subcommand)]
78
        cmd: LabelCmd,
79
    },
80
    /// Milestones: list, create, edit, close
81
    Milestone {
82
        #[command(subcommand)]
83
        cmd: MilestoneCmd,
84
    },
85
    /// Project boards of the repository's owner (or --owner): list,
86
    /// create, view, and cards
87
    Project {
88
        #[command(subcommand)]
89
        cmd: ProjectCmd,
90
        /// A user or organisation other than the repository's owner
91
        #[arg(long, global = true)]
92
        owner: Option<String>,
93
    },
94
    /// AI assistants of the repository (its admins), or with --org or
95
    /// --site of an organisation or the site
96
    Assistant {
97
        #[command(subcommand)]
98
        cmd: AssistantCmd,
99
        /// An organisation's assistants instead of the repository's
100
        #[arg(long, global = true)]
101
        org: Option<String>,
102
        /// The site's assistants (administrators)
103
        #[arg(long, global = true, conflicts_with = "org")]
104
        site: bool,
105
    },
106
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
107
    Api {
108
        /// A path under /api/v1
109
        path: String,
110
        /// The method
111
        #[arg(long, short = 'X', default_value = "GET")]
112
        method: String,
113
        /// A JSON body
114
        #[arg(long, short = 'd')]
115
        data: Option<String>,
116
    },
117
}
118
119
#[derive(Subcommand)]
120
enum AuthCmd {
121
    /// Sign in to a hub and make it the default: approve a code on the web
122
    /// (device sign-in), or give a token
123
    Login {
124
        /// The hub, e.g. https://oxygenhub.io
125
        #[arg(long = "with-hub", value_name = "URL")]
126
        url: String,
127
        /// An API token from the hub's Settings → Tokens, instead of
128
        /// approving a code ("-" reads it from stdin)
129
        #[arg(long)]
130
        token: Option<String>,
131
        /// The hub's CA certificate, when self-signed
132
        #[arg(long)]
133
        ca: Option<std::path::PathBuf>,
134
    },
135
    /// Who the token in use belongs to
136
    Status,
137
}
138
139
#[derive(Subcommand)]
140
enum RepoCmd {
141
    /// Name, description, visibility and default bookmark
142
    View,
143
}
144
145
#[derive(Subcommand)]
146
enum IssueCmd {
147
    /// Put labels on an issue or take them off (triage)
148
    Label(LabelChange),
149
    /// Open issues (or --state closed|all)
150
    List {
151
        #[arg(long, default_value = "open")]
152
        state: String,
153
    },
154
    /// One issue with its comments
155
    View { number: i64 },
156
    /// Open an issue
157
    Create {
158
        #[arg(long, short)]
159
        title: String,
160
        #[arg(long, short)]
161
        body: Option<String>,
162
        /// Read the body from a file ("-" for stdin)
163
        #[arg(long, short = 'F')]
164
        body_file: Option<String>,
165
        /// A label (repeatable)
166
        #[arg(long, short)]
167
        label: Vec<String>,
168
        /// Also put it on this board of the repository's owner
169
        #[arg(long, short)]
170
        project: Option<i64>,
171
        /// The board's column for it, by name (default: the first)
172
        #[arg(long, requires = "project")]
173
        column: Option<String>,
174
    },
175
    /// Close an issue
176
    Close {
177
        number: i64,
178
        /// `completed` or `not_planned`
179
        #[arg(long, default_value = "completed")]
180
        reason: String,
181
    },
182
    /// Reopen an issue
183
    Reopen { number: i64 },
184
    /// Change an issue's title or body (its author or triage), or its
185
    /// labels, assignees or milestone as whole sets (triage)
186
    Edit {
187
        number: i64,
188
        #[arg(long, short)]
189
        title: Option<String>,
190
        #[arg(long, short)]
191
        body: Option<String>,
192
        /// Read the body from a file ("-" for stdin)
193
        #[arg(long, short = 'F', conflicts_with = "body")]
194
        body_file: Option<String>,
195
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
196
        #[arg(long, short)]
197
        label: Vec<String>,
198
        /// Clear its labels
199
        #[arg(long, conflicts_with = "label")]
200
        no_labels: bool,
201
        /// The users it should be assigned to (repeatable)
202
        #[arg(long, short)]
203
        assignee: Vec<String>,
204
        /// Take everyone off it
205
        #[arg(long, conflicts_with = "assignee")]
206
        no_assignees: bool,
207
        /// A milestone's title ("" takes it out of its milestone)
208
        #[arg(long, short)]
209
        milestone: Option<String>,
210
    },
211
    /// Comment on an issue
212
    Comment {
213
        number: i64,
214
        #[arg(long, short)]
215
        body: String,
216
    },
217
}
218
219
#[derive(Subcommand)]
220
enum ProposalCmd {
221
    /// Open proposals (or --state draft|landed|closed|all)
222
    List {
223
        #[arg(long, default_value = "open")]
224
        state: String,
225
    },
226
    /// One proposal: its changes, approvals and whether it can land
227
    View { number: i64 },
228
    /// Propose a bookmark's changes for another bookmark
229
    Create {
230
        #[arg(long, short)]
231
        title: String,
232
        #[arg(long, short)]
233
        body: Option<String>,
234
        /// Read the body from a file ("-" for stdin)
235
        #[arg(long, short = 'F', conflicts_with = "body")]
236
        body_file: Option<String>,
237
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
238
        #[arg(long)]
239
        from: String,
240
        /// The bookmark to land them on (default: the repository's default bookmark)
241
        #[arg(long)]
242
        into: Option<String>,
243
        #[arg(long)]
244
        draft: bool,
245
    },
246
    /// Change a proposal's title or description (its author or a maintainer)
247
    Edit {
248
        number: i64,
249
        #[arg(long, short)]
250
        title: Option<String>,
251
        #[arg(long, short)]
252
        body: Option<String>,
253
        /// Read the body from a file ("-" for stdin)
254
        #[arg(long, short = 'F', conflicts_with = "body")]
255
        body_file: Option<String>,
256
    },
257
    /// Put labels on a proposal or take them off (triage)
258
    Label(LabelChange),
259
    /// Comment on a proposal's conversation
260
    Comment {
261
        number: i64,
262
        #[arg(long, short)]
263
        body: Option<String>,
264
        /// Read the comment from a file ("-" for stdin)
265
        #[arg(long, short = 'F', conflicts_with = "body")]
266
        body_file: Option<String>,
267
    },
268
    /// The checks on a proposal's projected state
269
    Checks { number: i64 },
270
    /// Land a proposal on its target, as the page's Land button does
271
    Land { number: i64 },
272
    /// Close a proposal without landing it, with an optional comment
273
    Close {
274
        number: i64,
275
        /// Say why, as a comment before it closes
276
        #[arg(long, short = 'm')]
277
        message: Option<String>,
278
    },
279
    /// Reopen a closed proposal
280
    Reopen { number: i64 },
281
}
282
283
#[derive(Subcommand)]
284
enum AssistantCmd {
285
    /// The assistants this level sees, its own and those inherited
286
    List,
287
    /// Add an assistant, or change the one of that name
288
    Add {
289
        /// How it shows on reviews (default: the provider's name)
290
        #[arg(long, default_value = "")]
291
        name: String,
292
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
293
        #[arg(long, default_value = "")]
294
        preset: String,
295
        /// The endpoint, when no preset or another one
296
        #[arg(long, default_value = "")]
297
        endpoint: String,
298
        /// chat-completions or anthropic-messages
299
        #[arg(long, default_value = "")]
300
        api: String,
301
        /// One the endpoint lists (`oh assistant models` shows them)
302
        #[arg(long)]
303
        model: String,
304
        /// The API key, read from this environment variable (never typed on the command line)
305
        #[arg(long, value_name = "VAR")]
306
        token_env: Option<String>,
307
        /// Add it turned off
308
        #[arg(long)]
309
        off: bool,
310
    },
311
    /// Remove this level's assistant of that name
312
    Remove { name: String },
313
    /// Show this level's prompt, and those it inherits
314
    Prompt {
315
        /// Set it from this file (`-` for standard input; an empty file clears it)
316
        #[arg(long, value_name = "FILE")]
317
        set: Option<std::path::PathBuf>,
318
    },
319
}
320
321
#[derive(Subcommand)]
322
enum LabelCmd {
323
    /// The repository's labels
324
    List,
325
    /// Create a label, or change the one of that name (triage)
326
    Create {
327
        name: String,
328
        /// `#rrggbb` (default: one the hub picks)
329
        #[arg(long)]
330
        colour: Option<String>,
331
        #[arg(long, short, default_value = "")]
332
        description: String,
333
    },
334
    /// Delete a label, taking it off every issue and proposal (triage)
335
    Delete { name: String },
336
}
337
338
#[derive(Subcommand)]
339
enum ProjectCmd {
340
    /// The owner's boards
341
    List,
342
    /// One board: its columns and cards
343
    View { number: i64 },
344
    /// Create a board (owner, or an organisation's members)
345
    Create {
346
        title: String,
347
        #[arg(long, short, default_value = "")]
348
        description: String,
349
        /// Only the owner (or the organisation's members) can see it
350
        #[arg(long)]
351
        private: bool,
352
    },
353
    /// Close a board
354
    Close { number: i64 },
355
    /// Reopen a board
356
    Reopen { number: i64 },
357
    /// Move a board to another owner you may make boards under (an
358
    /// organisation, say); it takes the next number there
359
    Transfer {
360
        number: i64,
361
        /// The new owner
362
        #[arg(long)]
363
        to: String,
364
    },
365
    /// Cards on a board: add, move, remove
366
    Card {
367
        #[command(subcommand)]
368
        cmd: CardCmd,
369
    },
370
}
371
372
#[derive(Subcommand)]
373
enum CardCmd {
374
    /// Put an issue or proposal on a board (`12` or `#12` in this
375
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
376
    /// or a note with --note
377
    Add {
378
        number: i64,
379
        /// The issue or proposal; a number means this repository's
380
        reference: Option<String>,
381
        /// A note card instead
382
        #[arg(long, conflicts_with = "reference")]
383
        note: Option<String>,
384
        /// The column, by name or id (default: the first)
385
        #[arg(long, short)]
386
        column: Option<String>,
387
    },
388
    /// Move a card to another column (by name or id)
389
    Move {
390
        number: i64,
391
        card: i64,
392
        #[arg(long, short)]
393
        column: String,
394
    },
395
    /// Take a card off a board
396
    Remove { number: i64, card: i64 },
397
}
398
399
#[derive(Subcommand)]
400
enum MilestoneCmd {
401
    /// The repository's milestones
402
    List,
403
    /// Create a milestone, or change the one of that title (triage)
404
    Create {
405
        title: String,
406
        #[arg(long, short, default_value = "")]
407
        description: String,
408
        /// Due date, YYYY-MM-DD
409
        #[arg(long)]
410
        due: Option<String>,
411
    },
412
    /// Change a milestone's title, description or due date (triage)
413
    Edit {
414
        title: String,
415
        #[arg(long, short)]
416
        rename: Option<String>,
417
        #[arg(long, short)]
418
        description: Option<String>,
419
        /// Due date, YYYY-MM-DD ("" for none)
420
        #[arg(long)]
421
        due: Option<String>,
422
    },
423
    /// Close a milestone
424
    Close { title: String },
425
    /// Reopen a milestone
426
    Reopen { title: String },
427
}
428
429
/// Labels to put on or take off an issue or proposal.
430
#[derive(clap::Args)]
431
struct LabelChange {
432
    number: i64,
433
    /// A label to add (repeatable)
434
    #[arg(long, short)]
435
    add: Vec<String>,
436
    /// A label to take off (repeatable)
437
    #[arg(long, short)]
438
    remove: Vec<String>,
439
}
440
441
impl LabelChange {
442
    /// The set after the change, from the one there now.
443
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
444
        if self.add.is_empty() && self.remove.is_empty() {
445
            bail!("say what to change: --add NAME or --remove NAME");
446
        }
447
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
448
        for a in &self.add {
449
            if !names.contains(a) {
450
                names.push(a.clone());
451
            }
452
        }
453
        Ok(names)
454
    }
455
}
456
457
fn label_names(labels: &[String]) -> String {
458
    if labels.is_empty() {
459
        ui::dim("no labels")
460
    } else {
461
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
462
    }
463
}
464
465
#[derive(Subcommand)]
466
enum CoverageCmd {
467
    /// Upload an LCOV or Cobertura report measured on this machine, as the
468
    /// coverage of a bookmark's current state (default: the default
469
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
470
    /// not measured by a runner, and sets no check from it
471
    Upload {
472
        file: std::path::PathBuf,
473
        #[arg(long)]
474
        bookmark: Option<String>,
475
        /// A change's full hash
476
        #[arg(long, conflicts_with = "bookmark")]
477
        change: Option<String>,
478
    },
479
}
480
481
#[derive(Subcommand)]
482
enum RunCmd {
483
    /// Recent runs, newest first
484
    List {
485
        #[arg(long, default_value_t = 20)]
486
        limit: i64,
487
    },
488
    /// A run and its jobs
489
    View { number: i64 },
490
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
491
    Start {
492
        #[arg(long)]
493
        bookmark: Option<String>,
494
        /// A change's full hash
495
        #[arg(long, conflicts_with = "bookmark")]
496
        change: Option<String>,
497
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
498
        #[arg(long = "job", value_name = "NAME")]
499
        jobs: Vec<String>,
500
        /// Wait for the run and exit 1 unless it passes
501
        #[arg(long)]
502
        watch: bool,
503
    },
504
    /// Follow a run until it finishes; exit 1 unless it passes
505
    Watch { number: i64 },
506
    /// A job's log
507
    Log { number: i64, job: String },
508
    /// Run a finished run's state again
509
    Rerun { number: i64 },
510
    /// Cancel a run still queued or running; its running jobs are stopped
511
    Cancel { number: i64 },
512
}
513
514
#[derive(Subcommand)]
515
enum ReleaseCmd {
516
    /// Releases, newest first
517
    List,
518
    /// Create a release on an existing tag
519
    Create {
520
        tag: String,
521
        #[arg(long, short)]
522
        title: Option<String>,
523
        /// Notes in Markdown (default: generated from the changes since the previous release)
524
        #[arg(long, short)]
525
        notes: Option<String>,
526
        #[arg(long)]
527
        prerelease: bool,
528
    },
529
    /// Change a release's title, notes or prerelease flag
530
    Edit {
531
        tag: String,
532
        #[arg(long, short)]
533
        title: Option<String>,
534
        /// New notes in Markdown ("-" reads them from stdin)
535
        #[arg(long, short)]
536
        notes: Option<String>,
537
        /// Mark it a prerelease (true) or not (false)
538
        #[arg(long)]
539
        prerelease: Option<bool>,
540
    },
541
    /// Attach files to a release
542
    Upload { tag: String, files: Vec<std::path::PathBuf> },
543
    /// The release's trust report: signatures, builds, receipts and audit
544
    Trust { tag: String },
545
}
546
547
fn main() {
548
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
549
    // other command-line tools do, instead of panicking on the failed
550
    // write (oxygenhub#92).
551
    #[cfg(unix)]
552
    unsafe {
553
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
554
    }
555
    let cli = Cli::parse();
556
    ui::init(cli.plain);
557
    match run(cli) {
558
        Ok(code) => std::process::exit(code),
559
        Err(e) => {
560
            eprintln!("{} {e:#}", ui::bad("error:"));
561
            std::process::exit(2);
562
        }
563
    }
564
}
565
566
fn enc(s: &str) -> String {
567
    let mut out = String::new();
568
    for b in s.bytes() {
569
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
570
            out.push(b as char);
571
        } else {
572
            out.push_str(&format!("%{b:02X}"));
573
        }
574
    }
575
    out
576
}
577
578
fn run(cli: Cli) -> Result<i32> {
579
    let cfg = Config::load()?;
580
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
581
        return login(cfg, url, token.clone(), ca.clone());
582
    }
583
    let here = std::env::current_dir()?;
584
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
585
    let c = Client::new(&t)?;
586
    let json = cli.json;
587
    match cli.cmd {
588
        Cmd::Auth { cmd: AuthCmd::Status } => {
589
            let me: serde_json::Value = c.get("/user")?;
590
            if json {
591
                println!("{me}");
592
            } else {
593
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
594
            }
595
            Ok(0)
596
        }
597
        Cmd::Auth { .. } => unreachable!(),
598
        Cmd::Api { path, method, data } => {
599
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
600
            let text = match data {
601
                Some(d) => c.send_text(
602
                    &method.to_uppercase(),
603
                    &path,
604
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
605
                )?,
606
                None => c.get_text(&path)?,
607
            };
608
            println!("{text}");
609
            Ok(0)
610
        }
611
        Cmd::Repo { cmd: RepoCmd::View } => {
612
            let path = t.repo_path()?;
613
            if json {
614
                println!("{}", c.get_text(&path)?);
615
                return Ok(0);
616
            }
617
            let r: serde_json::Value = c.get(&path)?;
618
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
619
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
620
                println!("{d}");
621
            }
622
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
623
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
624
            Ok(0)
625
        }
626
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
627
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
628
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
629
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
630
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
631
            let mut body = serde_json::json!({ "content": content });
632
            if let Some(b) = bookmark {
633
                body["bookmark"] = b.into();
634
            }
635
            if let Some(ch) = change {
636
                body["change"] = ch.into();
637
            }
638
            let base = t.repo_path()?;
639
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
640
            if json {
641
                println!("{}", serde_json::to_string(&r)?);
642
            } else {
643
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
644
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
645
                println!(
646
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
647
                    ui::ok("✔"),
648
                    r.lines_hit,
649
                    r.lines_found,
650
                    r.files,
651
                    ui::dim(&r.url)
652
                );
653
                if r.dropped > 0 {
654
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
655
                }
656
            }
657
            Ok(0)
658
        }
659
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
660
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
661
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
662
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
663
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
664
    }
665
}
666
667
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
668
    let hub = url.trim_end_matches('/').to_string();
669
    let token = match token.as_deref() {
670
        Some("-") => {
671
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
672
            let mut line = String::new();
673
            std::io::stdin().read_line(&mut line)?;
674
            line.trim().to_string()
675
        }
676
        Some(t) => t.to_string(),
677
        None => device_sign_in(&hub, ca.clone())?,
678
    };
679
    if token.is_empty() {
680
        bail!("no token given");
681
    }
682
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
683
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
684
    let account = me["username"].as_str().unwrap_or("?");
685
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
686
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
687
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
688
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
689
    cfg.default_hub = Some(hub.clone());
690
    cfg.save()?;
691
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
692
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
693
    Ok(0)
694
}
695
696
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
697
/// it on the web, and the token arrives here.
698
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
699
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
700
    let c = Client::new(&t)?;
701
    let host = std::fs::read_to_string("/etc/hostname")
702
        .ok()
703
        .or_else(|| std::env::var("COMPUTERNAME").ok())
704
        .map(|h| h.trim().to_string())
705
        .filter(|h| !h.is_empty());
706
    let client = match host {
707
        Some(h) => format!("oh on {h}"),
708
        None => "oh".to_string(),
709
    };
710
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
711
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
712
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
713
    if code != 200 {
714
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
715
    }
716
    let device = v["device_code"].as_str().context("no device code")?.to_string();
717
    let user = v["user_code"].as_str().unwrap_or("?");
718
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
719
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
720
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
721
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
722
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
723
    loop {
724
        std::thread::sleep(std::time::Duration::from_secs(interval));
725
        if std::time::Instant::now() > deadline {
726
            bail!("the code expired before it was approved; run oh auth login again");
727
        }
728
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
729
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
730
        if code == 200 {
731
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
732
        }
733
        match v["error"].as_str() {
734
            Some("authorization_pending") => {}
735
            Some("slow_down") => interval += 5,
736
            Some("access_denied") => bail!("the sign-in was denied on the web"),
737
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
738
            _ => bail!("signing in: HTTP {code}: {body}"),
739
        }
740
    }
741
}
742
743
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
744
    match (body, file) {
745
        (Some(b), _) => Ok(b),
746
        (None, Some(f)) if f == "-" => {
747
            let mut s = String::new();
748
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
749
            Ok(s)
750
        }
751
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
752
        (None, None) => Ok(String::new()),
753
    }
754
}
755
756
fn issue_line(i: &Issue) -> String {
757
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
758
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
759
    format!(
760
        "{glyph} {} {}{}{}",
761
        ui::dim(&format!("#{}", i.number)),
762
        i.title,
763
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
764
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
765
    )
766
}
767
768
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
769
    let base = t.repo_path()?;
770
    match cmd {
771
        IssueCmd::List { state } => {
772
            let path = format!("{base}/issues?state={}", enc(&state));
773
            if json {
774
                println!("{}", c.get_text(&path)?);
775
                return Ok(0);
776
            }
777
            let list: Vec<Issue> = c.get(&path)?;
778
            if list.is_empty() {
779
                println!("{}", ui::dim(&format!("No {state} issues.")));
780
            }
781
            for i in &list {
782
                println!("{}", issue_line(i));
783
            }
784
        }
785
        IssueCmd::View { number } => {
786
            let path = format!("{base}/issues/{number}");
787
            if json {
788
                println!("{}", c.get_text(&path)?);
789
                return Ok(0);
790
            }
791
            let i: Issue = c.get(&path)?;
792
            println!("{}", issue_line(&i));
793
            if !i.body.trim().is_empty() {
794
                println!("\n{}\n", i.body.trim_end());
795
            }
796
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
797
            for cm in comments {
798
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
799
            }
800
            println!("{}", ui::dim(&i.url));
801
        }
802
        IssueCmd::Create { title, body, body_file, label, project, column } => {
803
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
804
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
805
            if json {
806
                println!("{}", serde_json::to_string(&i)?);
807
            } else {
808
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
809
            }
810
            if let Some(n) = project {
811
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
812
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
813
                if !json {
814
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
815
                }
816
            }
817
        }
818
        IssueCmd::Close { number, reason } => {
819
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
820
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
821
        }
822
        IssueCmd::Reopen { number } => {
823
            let i: Issue =
824
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
825
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
826
        }
827
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
828
            let body = match (&body, &body_file) {
829
                (None, None) => None,
830
                _ => Some(body_of(body, body_file)?),
831
            };
832
            let labels = if no_labels {
833
                Some(Vec::new())
834
            } else if label.is_empty() {
835
                None
836
            } else {
837
                Some(label)
838
            };
839
            let assignees = if no_assignees {
840
                Some(Vec::new())
841
            } else if assignee.is_empty() {
842
                None
843
            } else {
844
                Some(assignee)
845
            };
846
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
847
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
848
            }
849
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
850
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
851
            if json {
852
                println!("{}", serde_json::to_string(&i)?);
853
            } else {
854
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
855
            }
856
        }
857
        IssueCmd::Label(change) => {
858
            let path = format!("{base}/issues/{}", change.number);
859
            let now: Issue = c.get(&path)?;
860
            let labels = change.apply(&now.labels)?;
861
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
862
            let i: Issue = c.send("PATCH", &path, &edit)?;
863
            if json {
864
                println!("{}", serde_json::to_string(&i)?);
865
            } else {
866
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
867
            }
868
        }
869
        IssueCmd::Comment { number, body } => {
870
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
871
            println!("{} commented on #{number}", ui::ok("✔"));
872
        }
873
    }
874
    Ok(0)
875
}
876
877
fn source_name(s: &hub_api::ProposalSource) -> String {
878
    match s {
879
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
880
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
881
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
882
    }
883
}
884
885
fn proposal_line(p: &Proposal) -> String {
886
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
887
    let glyph = match state.as_str() {
888
        "open" => ui::ok("●"),
889
        "draft" => ui::dim("◌"),
890
        "landed" => ui::strong("✔"),
891
        _ => ui::dim("○"),
892
    };
893
    format!(
894
        "{glyph} {} {} {}{}",
895
        ui::dim(&format!("#{}", p.number)),
896
        p.title,
897
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
898
        ui::dim(&format!(" · {} · {state}", p.author))
899
    )
900
}
901
902
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
903
    let base = t.repo_path()?;
904
    match cmd {
905
        ProposalCmd::List { state } => {
906
            let path = format!("{base}/proposals?state={state}");
907
            if json {
908
                println!("{}", c.get_text(&path)?);
909
                return Ok(0);
910
            }
911
            let list: Vec<Proposal> = c.get(&path)?;
912
            if list.is_empty() {
913
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
914
            }
915
            for p in &list {
916
                println!("{}", proposal_line(p));
917
            }
918
        }
919
        ProposalCmd::View { number } => {
920
            let path = format!("{base}/proposals/{number}");
921
            if json {
922
                println!("{}", c.get_text(&path)?);
923
                return Ok(0);
924
            }
925
            let p: Proposal = c.get(&path)?;
926
            println!("{}", proposal_line(&p));
927
            if !p.body.trim().is_empty() {
928
                println!("\n{}\n", p.body.trim_end());
929
            }
930
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
931
            for ch in &p.changes {
932
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
933
            }
934
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
935
            if p.landable {
936
                println!("{} can land", ui::ok("✔"));
937
            } else {
938
                for b in &p.blockers {
939
                    println!("{} {b}", ui::bad("✘"));
940
                }
941
            }
942
            if p.conflicted {
943
                println!("{} landing it would leave conflicts", ui::bad("!"));
944
            }
945
            println!("{}", ui::dim(&p.url));
946
        }
947
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
948
            let target = match into {
949
                Some(i) => i,
950
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
951
            };
952
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
953
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
954
            if json {
955
                println!("{}", serde_json::to_string(&p)?);
956
            } else {
957
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
958
            }
959
        }
960
        ProposalCmd::Edit { number, title, body, body_file } => {
961
            let body = match (&body, &body_file) {
962
                (None, None) => None,
963
                _ => Some(body_of(body, body_file)?),
964
            };
965
            if title.is_none() && body.is_none() {
966
                bail!("say what to change: --title, --body or --body-file");
967
            }
968
            let edit = hub_api::ProposalEdit { title, body, labels: None, state: None };
969
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
970
            if json {
971
                println!("{}", serde_json::to_string(&p)?);
972
            } else {
973
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
974
            }
975
        }
976
        ProposalCmd::Label(change) => {
977
            let path = format!("{base}/proposals/{}", change.number);
978
            let now: Proposal = c.get(&path)?;
979
            let labels = change.apply(&now.labels)?;
980
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
981
            let p: Proposal = c.send("PATCH", &path, &edit)?;
982
            if json {
983
                println!("{}", serde_json::to_string(&p)?);
984
            } else {
985
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
986
            }
987
        }
988
        ProposalCmd::Comment { number, body, body_file } => {
989
            let body = body_of(body, body_file)?;
990
            if body.trim().is_empty() {
991
                bail!("give the comment with --body or --body-file");
992
            }
993
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
994
            println!("{} commented on #{number}", ui::ok("✔"));
995
        }
996
        ProposalCmd::Land { number } => {
997
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &serde_json::json!({}))?;
998
            if json {
999
                println!("{}", serde_json::to_string(&p)?);
1000
            } else {
1001
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
1002
            }
1003
        }
1004
        ProposalCmd::Close { number, message } => {
1005
            if let Some(body) = message {
1006
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1007
            }
1008
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1009
            if json {
1010
                println!("{}", serde_json::to_string(&p)?);
1011
            } else {
1012
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1013
            }
1014
        }
1015
        ProposalCmd::Reopen { number } => {
1016
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1017
            if json {
1018
                println!("{}", serde_json::to_string(&p)?);
1019
            } else {
1020
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
1021
            }
1022
        }
1023
        ProposalCmd::Checks { number } => {
1024
            let path = format!("{base}/proposals/{number}/checks");
1025
            if json {
1026
                println!("{}", c.get_text(&path)?);
1027
                return Ok(0);
1028
            }
1029
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1030
            if checks.is_empty() {
1031
                println!("{}", ui::dim("No checks yet."));
1032
            }
1033
            for ch in checks {
1034
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1035
            }
1036
        }
1037
    }
1038
    Ok(0)
1039
}
1040
1041
fn run_line(r: &FlowRun) -> String {
1042
    let what =
1043
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1044
    format!(
1045
        "{} {} {} {}",
1046
        ui::status(&r.status),
1047
        ui::dim(&format!("#{}", r.number)),
1048
        what,
1049
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1050
    )
1051
}
1052
1053
fn print_run(r: &FlowRun) {
1054
    println!("{}", run_line(r));
1055
    for j in &r.jobs {
1056
        let dur = match (j.started_ms, j.finished_ms) {
1057
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1058
            _ => String::new(),
1059
        };
1060
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1061
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1062
        // Why a queued job no runner can take waits (oxygenhub#28), and
1063
        // why a job ran where it did (oxygenflow#42).
1064
        if j.status == "queued" && !j.waiting.is_empty() {
1065
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1066
        } else if !j.placed.is_empty() {
1067
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1068
        }
1069
    }
1070
    if !r.error.is_empty() {
1071
        println!("{}", ui::bad(&r.error));
1072
    }
1073
    println!("{}", ui::dim(&r.url));
1074
}
1075
1076
fn live(status: &str) -> bool {
1077
    matches!(status, "queued" | "running")
1078
}
1079
1080
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
1081
    let path = format!("{base}/flow/runs/{number}");
1082
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1083
    loop {
1084
        let r: FlowRun = c.get(&path)?;
1085
        if !json {
1086
            for j in &r.jobs {
1087
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1088
                if seen.get(&j.name) != Some(&shown) {
1089
                    println!("{} {}", ui::status(&j.status), j.name);
1090
                    if j.status == "queued" && !j.waiting.is_empty() {
1091
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1092
                    }
1093
                    seen.insert(j.name.clone(), shown);
1094
                }
1095
            }
1096
        }
1097
        if !live(&r.status) {
1098
            if json {
1099
                println!("{}", serde_json::to_string(&r)?);
1100
            } else {
1101
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1102
            }
1103
            return Ok(if r.status == "passed" { 0 } else { 1 });
1104
        }
1105
        std::thread::sleep(Duration::from_secs(3));
1106
    }
1107
}
1108
1109
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1110
    let base = t.repo_path()?;
1111
    match cmd {
1112
        RunCmd::List { limit } => {
1113
            let path = format!("{base}/flow/runs?limit={limit}");
1114
            if json {
1115
                println!("{}", c.get_text(&path)?);
1116
                return Ok(0);
1117
            }
1118
            let runs: Vec<FlowRun> = c.get(&path)?;
1119
            if runs.is_empty() {
1120
                println!("{}", ui::dim("No runs yet."));
1121
            }
1122
            for r in &runs {
1123
                println!("{}", run_line(r));
1124
            }
1125
        }
1126
        RunCmd::View { number } => {
1127
            let path = format!("{base}/flow/runs/{number}");
1128
            if json {
1129
                println!("{}", c.get_text(&path)?);
1130
                return Ok(0);
1131
            }
1132
            print_run(&c.get(&path)?);
1133
        }
1134
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
1135
            let mut body = match (bookmark, change) {
1136
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1137
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1138
                (None, None) => serde_json::json!({}),
1139
            };
1140
            if !jobs.is_empty() {
1141
                body["jobs"] = serde_json::json!(jobs);
1142
            }
1143
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1144
            let n = started["number"].as_i64().context("the hub named no run")?;
1145
            if !json || !follow {
1146
                if json {
1147
                    println!("{started}");
1148
                } else {
1149
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1150
                }
1151
            }
1152
            if follow {
1153
                return watch(c, &base, n, json);
1154
            }
1155
        }
1156
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1157
        RunCmd::Log { number, job } => {
1158
            let mut after = 0;
1159
            loop {
1160
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1161
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1162
                if lines.is_empty() {
1163
                    break;
1164
                }
1165
                for l in &lines {
1166
                    if json {
1167
                        println!("{}", serde_json::to_string(l)?);
1168
                    } else if l.stream == "flow" {
1169
                        println!("{}", ui::dim(&l.text));
1170
                    } else {
1171
                        println!("{}", l.text);
1172
                    }
1173
                }
1174
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1175
            }
1176
        }
1177
        RunCmd::Rerun { number } => {
1178
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1179
            if json {
1180
                println!("{started}");
1181
            } else {
1182
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
1183
            }
1184
        }
1185
        RunCmd::Cancel { number } => {
1186
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
1187
            if json {
1188
                println!("{done}");
1189
            } else {
1190
                println!("{} cancelled run #{number}", ui::ok("✔"));
1191
            }
1192
        }
1193
    }
1194
    Ok(0)
1195
}
1196
1197
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
1198
    let base = t.repo_path()?;
1199
    match cmd {
1200
        LabelCmd::List => {
1201
            let path = format!("{base}/labels");
1202
            if json {
1203
                println!("{}", c.get_text(&path)?);
1204
                return Ok(0);
1205
            }
1206
            let labels: Vec<hub_api::Label> = c.get(&path)?;
1207
            if labels.is_empty() {
1208
                println!("{}", ui::dim("No labels."));
1209
            }
1210
            for l in labels {
1211
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
1212
            }
1213
        }
1214
        LabelCmd::Create { name, colour, description } => {
1215
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
1216
            if json {
1217
                println!("{}", serde_json::to_string(&l)?);
1218
            } else {
1219
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
1220
            }
1221
        }
1222
        LabelCmd::Delete { name } => {
1223
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
1224
            println!("{} deleted label {name}", ui::ok("✔"));
1225
        }
1226
    }
1227
    Ok(0)
1228
}
1229
1230
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
1231
    let base = match (&org, site) {
1232
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
1233
        (None, true) => "/admin/assistants".to_string(),
1234
        (None, false) => format!("{}/assistants", t.repo_path()?),
1235
    };
1236
    match cmd {
1237
        AssistantCmd::List => {
1238
            if json {
1239
                println!("{}", c.get_text(&base)?);
1240
                return Ok(0);
1241
            }
1242
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
1243
            if list.is_empty() {
1244
                println!("{}", ui::dim("No assistants."));
1245
            }
1246
            for a in list {
1247
                let state = if a.enabled && !a.off_above {
1248
                    ui::ok("on")
1249
                } else if a.off_above {
1250
                    ui::dim("off above")
1251
                } else {
1252
                    ui::dim("off")
1253
                };
1254
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
1255
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1256
            }
1257
        }
1258
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
1259
            let token = match token_env {
1260
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
1261
                None => String::new(),
1262
            };
1263
            let body =
1264
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
1265
            let r: serde_json::Value = c.send("POST", &base, &body)?;
1266
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1267
        }
1268
        AssistantCmd::Remove { name } => {
1269
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
1270
            println!("{} removed {name}", ui::ok("✔"));
1271
        }
1272
        AssistantCmd::Prompt { set } => {
1273
            let p: hub_api::AssistantPrompt = match set {
1274
                Some(path) => {
1275
                    let text = if path.as_os_str() == "-" {
1276
                        let mut s = String::new();
1277
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1278
                        s
1279
                    } else {
1280
                        std::fs::read_to_string(&path)?
1281
                    };
1282
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1283
                }
1284
                None => c.get(&format!("{base}/prompt"))?,
1285
            };
1286
            if json {
1287
                println!("{}", serde_json::to_string(&p)?);
1288
                return Ok(0);
1289
            }
1290
            for (from, text) in &p.inherited {
1291
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
1292
            }
1293
            if p.prompt.is_empty() {
1294
                println!("{}", ui::dim("No prompt of its own."));
1295
            } else {
1296
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
1297
            }
1298
        }
1299
    }
1300
    Ok(0)
1301
}
1302
1303
fn project_line(p: &hub_api::Project) -> String {
1304
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
1305
    let private = if p.public { "" } else { " · private" };
1306
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
1307
}
1308
1309
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
1310
    let owner = match owner {
1311
        Some(o) => o,
1312
        None => t.repo()?.0.to_string(),
1313
    };
1314
    let base = format!("/projects/{}", enc(&owner));
1315
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
1316
        let p: hub_api::Project =
1317
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
1318
        if json {
1319
            println!("{}", serde_json::to_string(&p)?);
1320
        } else {
1321
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
1322
        }
1323
        Ok(())
1324
    };
1325
    match cmd {
1326
        ProjectCmd::List => {
1327
            if json {
1328
                println!("{}", c.get_text(&base)?);
1329
                return Ok(0);
1330
            }
1331
            let list: Vec<hub_api::Project> = c.get(&base)?;
1332
            if list.is_empty() {
1333
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
1334
            }
1335
            for p in &list {
1336
                println!("{}", project_line(p));
1337
            }
1338
        }
1339
        ProjectCmd::View { number } => {
1340
            let path = format!("{base}/{number}");
1341
            if json {
1342
                println!("{}", c.get_text(&path)?);
1343
                return Ok(0);
1344
            }
1345
            let b: hub_api::Board = c.get(&path)?;
1346
            println!("{}", project_line(&b.project));
1347
            if !b.project.description.is_empty() {
1348
                println!("{}", b.project.description);
1349
            }
1350
            for col in &b.columns {
1351
                println!();
1352
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
1353
                if col.cards.is_empty() {
1354
                    println!("  {}", ui::dim("(empty)"));
1355
                }
1356
                for card in &col.cards {
1357
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
1358
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
1359
                    println!("  {} {what}{st}  {}", ui::dim(&format!("{:>4}", card.id)), card.title);
1360
                }
1361
            }
1362
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1363
        }
1364
        ProjectCmd::Create { title, description, private } => {
1365
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
1366
            if json {
1367
                println!("{}", serde_json::to_string(&p)?);
1368
            } else {
1369
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
1370
            }
1371
        }
1372
        ProjectCmd::Close { number } => state(number, true, "closed")?,
1373
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
1374
        ProjectCmd::Transfer { number, to } => {
1375
            let p: hub_api::Project =
1376
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
1377
            if json {
1378
                println!("{}", serde_json::to_string(&p)?);
1379
            } else {
1380
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
1381
            }
1382
        }
1383
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1384
            // The hub names a card's issue as `repo#N` among the owner's
1385
            // repositories.
1386
            let reference = match reference {
1387
                None => String::new(),
1388
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
1389
                    Some((o, rest)) if o == owner => rest.to_string(),
1390
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
1391
                    None => r,
1392
                },
1393
                Some(r) => {
1394
                    let n = r.trim_start_matches('#');
1395
                    if n.parse::<i64>().is_err() {
1396
                        bail!("{r}: give an issue or proposal number, or NAME#N");
1397
                    }
1398
                    format!("{}#{n}", t.repo()?.1)
1399
                }
1400
            };
1401
            let note = note.unwrap_or_default();
1402
            if reference.is_empty() && note.is_empty() {
1403
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
1404
            }
1405
            let card: hub_api::ProjectCard =
1406
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
1407
            if json {
1408
                println!("{}", serde_json::to_string(&card)?);
1409
            } else {
1410
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
1411
            }
1412
        }
1413
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column } } => {
1414
            c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
1415
            println!("{} card {card} moved to {column}", ui::ok("✔"));
1416
        }
1417
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
1418
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
1419
            println!("{} card {card} removed", ui::ok("✔"));
1420
        }
1421
    }
1422
    Ok(0)
1423
}
1424
1425
fn milestone_line(m: &hub_api::Milestone) -> String {
1426
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
1427
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
1428
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
1429
}
1430
1431
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
1432
    let base = t.repo_path()?;
1433
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
1434
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
1435
        if json {
1436
            println!("{}", serde_json::to_string(&m)?);
1437
        } else {
1438
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
1439
        }
1440
        Ok(())
1441
    };
1442
    match cmd {
1443
        MilestoneCmd::List => {
1444
            let path = format!("{base}/milestones");
1445
            if json {
1446
                println!("{}", c.get_text(&path)?);
1447
                return Ok(0);
1448
            }
1449
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
1450
            if list.is_empty() {
1451
                println!("{}", ui::dim("No milestones."));
1452
            }
1453
            for m in &list {
1454
                println!("{}", milestone_line(m));
1455
            }
1456
        }
1457
        MilestoneCmd::Create { title, description, due } => {
1458
            let m: hub_api::Milestone =
1459
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
1460
            if json {
1461
                println!("{}", serde_json::to_string(&m)?);
1462
            } else {
1463
                println!("{} milestone {}", ui::ok("✔"), m.title);
1464
            }
1465
        }
1466
        MilestoneCmd::Edit { title, rename, description, due } => {
1467
            if rename.is_none() && description.is_none() && due.is_none() {
1468
                bail!("say what to change: --rename, --description or --due");
1469
            }
1470
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1471
        }
1472
        MilestoneCmd::Close { title } => {
1473
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1474
        }
1475
        MilestoneCmd::Reopen { title } => {
1476
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
1477
        }
1478
    }
1479
    Ok(0)
1480
}
1481
1482
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
1483
    let base = t.repo_path()?;
1484
    match cmd {
1485
        ReleaseCmd::List => {
1486
            let path = format!("{base}/releases");
1487
            if json {
1488
                println!("{}", c.get_text(&path)?);
1489
                return Ok(0);
1490
            }
1491
            let list: Vec<Release> = c.get(&path)?;
1492
            if list.is_empty() {
1493
                println!("{}", ui::dim("No releases."));
1494
            }
1495
            for r in &list {
1496
                println!(
1497
                    "{} {} {}{}",
1498
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
1499
                    ui::strong(&r.tag),
1500
                    r.title,
1501
                    ui::dim(&format!(
1502
                        " · {} asset{} · {}",
1503
                        r.assets.len(),
1504
                        if r.assets.len() == 1 { "" } else { "s" },
1505
                        ui::ago(r.created_ms)
1506
                    ))
1507
                );
1508
            }
1509
        }
1510
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
1511
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
1512
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
1513
            if json {
1514
                println!("{}", serde_json::to_string(&r)?);
1515
            } else {
1516
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1517
            }
1518
        }
1519
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
1520
            let notes = match notes.as_deref() {
1521
                Some("-") => Some(body_of(None, Some("-".into()))?),
1522
                _ => notes,
1523
            };
1524
            if title.is_none() && notes.is_none() && prerelease.is_none() {
1525
                bail!("say what to change: --title, --notes or --prerelease");
1526
            }
1527
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
1528
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
1529
            if json {
1530
                println!("{}", serde_json::to_string(&r)?);
1531
            } else {
1532
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1533
            }
1534
        }
1535
        ReleaseCmd::Upload { tag, files } => {
1536
            if files.is_empty() {
1537
                bail!("name the files to attach");
1538
            }
1539
            for f in files {
1540
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
1541
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
1542
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
1543
                println!("{} attached {name} to {tag}", ui::ok("✔"));
1544
            }
1545
        }
1546
        ReleaseCmd::Trust { tag } => {
1547
            let path = format!("{base}/releases/trust/{}", enc(&tag));
1548
            if json {
1549
                println!("{}", c.get_text(&path)?);
1550
                return Ok(0);
1551
            }
1552
            let r: serde_json::Value = c.get(&path)?;
1553
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
1554
            let mut worst = 0;
1555
            for ch in r["audit"].as_array().into_iter().flatten() {
1556
                let v = ch["verdict"].as_str().unwrap_or("");
1557
                worst = worst.max(match v {
1558
                    "fail" => 2,
1559
                    "warn" => 1,
1560
                    _ => 0,
1561
                });
1562
                let g = match v {
1563
                    "pass" => ui::ok("✔"),
1564
                    "warn" => ui::warn("!"),
1565
                    _ => ui::bad("✘"),
1566
                };
1567
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
1568
            }
1569
            return Ok(if worst == 2 { 1 } else { 0 });
1570
        }
1571
    }
1572
    Ok(0)
1573
}