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