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