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