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