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