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