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