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