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