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