OXYGENHUB
# 73ef9f767132 oxygenhub / crates / oh / src / main.rs
59.4 KiB · Rust · last changed Placement ranks runners and says why a job ran where it did 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), and
1035
        // why a job ran where it did (oxygenflow#42).
1036
        if j.status == "queued" && !j.waiting.is_empty() {
1037
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1038
        } else if !j.placed.is_empty() {
1039
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1040
        }
1041
    }
1042
    if !r.error.is_empty() {
1043
        println!("{}", ui::bad(&r.error));
1044
    }
1045
    println!("{}", ui::dim(&r.url));
1046
}
1047
1048
fn live(status: &str) -> bool {
1049
    matches!(status, "queued" | "running")
1050
}
1051
1052
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
1053
    let path = format!("{base}/flow/runs/{number}");
1054
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1055
    loop {
1056
        let r: FlowRun = c.get(&path)?;
1057
        if !json {
1058
            for j in &r.jobs {
1059
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1060
                if seen.get(&j.name) != Some(&shown) {
1061
                    println!("{} {}", ui::status(&j.status), j.name);
1062
                    if j.status == "queued" && !j.waiting.is_empty() {
1063
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1064
                    }
1065
                    seen.insert(j.name.clone(), shown);
1066
                }
1067
            }
1068
        }
1069
        if !live(&r.status) {
1070
            if json {
1071
                println!("{}", serde_json::to_string(&r)?);
1072
            } else {
1073
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1074
            }
1075
            return Ok(if r.status == "passed" { 0 } else { 1 });
1076
        }
1077
        std::thread::sleep(Duration::from_secs(3));
1078
    }
1079
}
1080
1081
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1082
    let base = t.repo_path()?;
1083
    match cmd {
1084
        RunCmd::List { limit } => {
1085
            let path = format!("{base}/flow/runs?limit={limit}");
1086
            if json {
1087
                println!("{}", c.get_text(&path)?);
1088
                return Ok(0);
1089
            }
1090
            let runs: Vec<FlowRun> = c.get(&path)?;
1091
            if runs.is_empty() {
1092
                println!("{}", ui::dim("No runs yet."));
1093
            }
1094
            for r in &runs {
1095
                println!("{}", run_line(r));
1096
            }
1097
        }
1098
        RunCmd::View { number } => {
1099
            let path = format!("{base}/flow/runs/{number}");
1100
            if json {
1101
                println!("{}", c.get_text(&path)?);
1102
                return Ok(0);
1103
            }
1104
            print_run(&c.get(&path)?);
1105
        }
1106
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
1107
            let mut body = match (bookmark, change) {
1108
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1109
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1110
                (None, None) => serde_json::json!({}),
1111
            };
1112
            if !jobs.is_empty() {
1113
                body["jobs"] = serde_json::json!(jobs);
1114
            }
1115
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1116
            let n = started["number"].as_i64().context("the hub named no run")?;
1117
            if !json || !follow {
1118
                if json {
1119
                    println!("{started}");
1120
                } else {
1121
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1122
                }
1123
            }
1124
            if follow {
1125
                return watch(c, &base, n, json);
1126
            }
1127
        }
1128
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1129
        RunCmd::Log { number, job } => {
1130
            let mut after = 0;
1131
            loop {
1132
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1133
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1134
                if lines.is_empty() {
1135
                    break;
1136
                }
1137
                for l in &lines {
1138
                    if json {
1139
                        println!("{}", serde_json::to_string(l)?);
1140
                    } else if l.stream == "flow" {
1141
                        println!("{}", ui::dim(&l.text));
1142
                    } else {
1143
                        println!("{}", l.text);
1144
                    }
1145
                }
1146
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1147
            }
1148
        }
1149
        RunCmd::Rerun { number } => {
1150
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1151
            if json {
1152
                println!("{started}");
1153
            } else {
1154
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
1155
            }
1156
        }
1157
        RunCmd::Cancel { number } => {
1158
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
1159
            if json {
1160
                println!("{done}");
1161
            } else {
1162
                println!("{} cancelled run #{number}", ui::ok("✔"));
1163
            }
1164
        }
1165
    }
1166
    Ok(0)
1167
}
1168
1169
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
1170
    let base = t.repo_path()?;
1171
    match cmd {
1172
        LabelCmd::List => {
1173
            let path = format!("{base}/labels");
1174
            if json {
1175
                println!("{}", c.get_text(&path)?);
1176
                return Ok(0);
1177
            }
1178
            let labels: Vec<hub_api::Label> = c.get(&path)?;
1179
            if labels.is_empty() {
1180
                println!("{}", ui::dim("No labels."));
1181
            }
1182
            for l in labels {
1183
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
1184
            }
1185
        }
1186
        LabelCmd::Create { name, colour, description } => {
1187
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
1188
            if json {
1189
                println!("{}", serde_json::to_string(&l)?);
1190
            } else {
1191
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
1192
            }
1193
        }
1194
        LabelCmd::Delete { name } => {
1195
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
1196
            println!("{} deleted label {name}", ui::ok("✔"));
1197
        }
1198
    }
1199
    Ok(0)
1200
}
1201
1202
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
1203
    let base = match (&org, site) {
1204
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
1205
        (None, true) => "/admin/assistants".to_string(),
1206
        (None, false) => format!("{}/assistants", t.repo_path()?),
1207
    };
1208
    match cmd {
1209
        AssistantCmd::List => {
1210
            if json {
1211
                println!("{}", c.get_text(&base)?);
1212
                return Ok(0);
1213
            }
1214
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
1215
            if list.is_empty() {
1216
                println!("{}", ui::dim("No assistants."));
1217
            }
1218
            for a in list {
1219
                let state = if a.enabled && !a.off_above {
1220
                    ui::ok("on")
1221
                } else if a.off_above {
1222
                    ui::dim("off above")
1223
                } else {
1224
                    ui::dim("off")
1225
                };
1226
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
1227
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1228
            }
1229
        }
1230
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
1231
            let token = match token_env {
1232
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
1233
                None => String::new(),
1234
            };
1235
            let body =
1236
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
1237
            let r: serde_json::Value = c.send("POST", &base, &body)?;
1238
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1239
        }
1240
        AssistantCmd::Remove { name } => {
1241
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
1242
            println!("{} removed {name}", ui::ok("✔"));
1243
        }
1244
        AssistantCmd::Prompt { set } => {
1245
            let p: hub_api::AssistantPrompt = match set {
1246
                Some(path) => {
1247
                    let text = if path.as_os_str() == "-" {
1248
                        let mut s = String::new();
1249
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1250
                        s
1251
                    } else {
1252
                        std::fs::read_to_string(&path)?
1253
                    };
1254
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1255
                }
1256
                None => c.get(&format!("{base}/prompt"))?,
1257
            };
1258
            if json {
1259
                println!("{}", serde_json::to_string(&p)?);
1260
                return Ok(0);
1261
            }
1262
            for (from, text) in &p.inherited {
1263
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
1264
            }
1265
            if p.prompt.is_empty() {
1266
                println!("{}", ui::dim("No prompt of its own."));
1267
            } else {
1268
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
1269
            }
1270
        }
1271
    }
1272
    Ok(0)
1273
}
1274
1275
fn project_line(p: &hub_api::Project) -> String {
1276
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
1277
    let private = if p.public { "" } else { " · private" };
1278
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
1279
}
1280
1281
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
1282
    let owner = match owner {
1283
        Some(o) => o,
1284
        None => t.repo()?.0.to_string(),
1285
    };
1286
    let base = format!("/projects/{}", enc(&owner));
1287
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
1288
        let p: hub_api::Project =
1289
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
1290
        if json {
1291
            println!("{}", serde_json::to_string(&p)?);
1292
        } else {
1293
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
1294
        }
1295
        Ok(())
1296
    };
1297
    match cmd {
1298
        ProjectCmd::List => {
1299
            if json {
1300
                println!("{}", c.get_text(&base)?);
1301
                return Ok(0);
1302
            }
1303
            let list: Vec<hub_api::Project> = c.get(&base)?;
1304
            if list.is_empty() {
1305
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
1306
            }
1307
            for p in &list {
1308
                println!("{}", project_line(p));
1309
            }
1310
        }
1311
        ProjectCmd::View { number } => {
1312
            let path = format!("{base}/{number}");
1313
            if json {
1314
                println!("{}", c.get_text(&path)?);
1315
                return Ok(0);
1316
            }
1317
            let b: hub_api::Board = c.get(&path)?;
1318
            println!("{}", project_line(&b.project));
1319
            if !b.project.description.is_empty() {
1320
                println!("{}", b.project.description);
1321
            }
1322
            for col in &b.columns {
1323
                println!();
1324
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
1325
                if col.cards.is_empty() {
1326
                    println!("  {}", ui::dim("(empty)"));
1327
                }
1328
                for card in &col.cards {
1329
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
1330
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
1331
                    println!("  {} {what}{st}  {}", ui::dim(&format!("{:>4}", card.id)), card.title);
1332
                }
1333
            }
1334
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1335
        }
1336
        ProjectCmd::Create { title, description, private } => {
1337
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
1338
            if json {
1339
                println!("{}", serde_json::to_string(&p)?);
1340
            } else {
1341
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
1342
            }
1343
        }
1344
        ProjectCmd::Close { number } => state(number, true, "closed")?,
1345
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
1346
        ProjectCmd::Transfer { number, to } => {
1347
            let p: hub_api::Project =
1348
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
1349
            if json {
1350
                println!("{}", serde_json::to_string(&p)?);
1351
            } else {
1352
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
1353
            }
1354
        }
1355
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1356
            // The hub names a card's issue as `repo#N` among the owner's
1357
            // repositories.
1358
            let reference = match reference {
1359
                None => String::new(),
1360
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
1361
                    Some((o, rest)) if o == owner => rest.to_string(),
1362
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
1363
                    None => r,
1364
                },
1365
                Some(r) => {
1366
                    let n = r.trim_start_matches('#');
1367
                    if n.parse::<i64>().is_err() {
1368
                        bail!("{r}: give an issue or proposal number, or NAME#N");
1369
                    }
1370
                    format!("{}#{n}", t.repo()?.1)
1371
                }
1372
            };
1373
            let note = note.unwrap_or_default();
1374
            if reference.is_empty() && note.is_empty() {
1375
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
1376
            }
1377
            let card: hub_api::ProjectCard =
1378
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
1379
            if json {
1380
                println!("{}", serde_json::to_string(&card)?);
1381
            } else {
1382
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
1383
            }
1384
        }
1385
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column } } => {
1386
            c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
1387
            println!("{} card {card} moved to {column}", ui::ok("✔"));
1388
        }
1389
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
1390
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
1391
            println!("{} card {card} removed", ui::ok("✔"));
1392
        }
1393
    }
1394
    Ok(0)
1395
}
1396
1397
fn milestone_line(m: &hub_api::Milestone) -> String {
1398
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
1399
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
1400
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
1401
}
1402
1403
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
1404
    let base = t.repo_path()?;
1405
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
1406
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
1407
        if json {
1408
            println!("{}", serde_json::to_string(&m)?);
1409
        } else {
1410
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
1411
        }
1412
        Ok(())
1413
    };
1414
    match cmd {
1415
        MilestoneCmd::List => {
1416
            let path = format!("{base}/milestones");
1417
            if json {
1418
                println!("{}", c.get_text(&path)?);
1419
                return Ok(0);
1420
            }
1421
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
1422
            if list.is_empty() {
1423
                println!("{}", ui::dim("No milestones."));
1424
            }
1425
            for m in &list {
1426
                println!("{}", milestone_line(m));
1427
            }
1428
        }
1429
        MilestoneCmd::Create { title, description, due } => {
1430
            let m: hub_api::Milestone =
1431
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
1432
            if json {
1433
                println!("{}", serde_json::to_string(&m)?);
1434
            } else {
1435
                println!("{} milestone {}", ui::ok("✔"), m.title);
1436
            }
1437
        }
1438
        MilestoneCmd::Edit { title, rename, description, due } => {
1439
            if rename.is_none() && description.is_none() && due.is_none() {
1440
                bail!("say what to change: --rename, --description or --due");
1441
            }
1442
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1443
        }
1444
        MilestoneCmd::Close { title } => {
1445
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1446
        }
1447
        MilestoneCmd::Reopen { title } => {
1448
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
1449
        }
1450
    }
1451
    Ok(0)
1452
}
1453
1454
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
1455
    let base = t.repo_path()?;
1456
    match cmd {
1457
        ReleaseCmd::List => {
1458
            let path = format!("{base}/releases");
1459
            if json {
1460
                println!("{}", c.get_text(&path)?);
1461
                return Ok(0);
1462
            }
1463
            let list: Vec<Release> = c.get(&path)?;
1464
            if list.is_empty() {
1465
                println!("{}", ui::dim("No releases."));
1466
            }
1467
            for r in &list {
1468
                println!(
1469
                    "{} {} {}{}",
1470
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
1471
                    ui::strong(&r.tag),
1472
                    r.title,
1473
                    ui::dim(&format!(
1474
                        " · {} asset{} · {}",
1475
                        r.assets.len(),
1476
                        if r.assets.len() == 1 { "" } else { "s" },
1477
                        ui::ago(r.created_ms)
1478
                    ))
1479
                );
1480
            }
1481
        }
1482
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
1483
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
1484
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
1485
            if json {
1486
                println!("{}", serde_json::to_string(&r)?);
1487
            } else {
1488
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1489
            }
1490
        }
1491
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
1492
            let notes = match notes.as_deref() {
1493
                Some("-") => Some(body_of(None, Some("-".into()))?),
1494
                _ => notes,
1495
            };
1496
            if title.is_none() && notes.is_none() && prerelease.is_none() {
1497
                bail!("say what to change: --title, --notes or --prerelease");
1498
            }
1499
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
1500
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
1501
            if json {
1502
                println!("{}", serde_json::to_string(&r)?);
1503
            } else {
1504
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1505
            }
1506
        }
1507
        ReleaseCmd::Upload { tag, files } => {
1508
            if files.is_empty() {
1509
                bail!("name the files to attach");
1510
            }
1511
            for f in files {
1512
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
1513
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
1514
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
1515
                println!("{} attached {name} to {tag}", ui::ok("✔"));
1516
            }
1517
        }
1518
        ReleaseCmd::Trust { tag } => {
1519
            let path = format!("{base}/releases/trust/{}", enc(&tag));
1520
            if json {
1521
                println!("{}", c.get_text(&path)?);
1522
                return Ok(0);
1523
            }
1524
            let r: serde_json::Value = c.get(&path)?;
1525
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
1526
            let mut worst = 0;
1527
            for ch in r["audit"].as_array().into_iter().flatten() {
1528
                let v = ch["verdict"].as_str().unwrap_or("");
1529
                worst = worst.max(match v {
1530
                    "fail" => 2,
1531
                    "warn" => 1,
1532
                    _ => 0,
1533
                });
1534
                let g = match v {
1535
                    "pass" => ui::ok("✔"),
1536
                    "warn" => ui::warn("!"),
1537
                    _ => ui::bad("✘"),
1538
                };
1539
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
1540
            }
1541
            return Ok(if worst == 2 { 1 } else { 0 });
1542
        }
1543
    }
1544
    Ok(0)
1545
}