OXYGENHUB
# 7829b7c7bb59 oxygenhub / crates / oh / src / main.rs
56.8 KiB · Rust · last changed Flow: say why a queued job waits, in oh and its check 26 days ago source blame history raw
5c6e92fd Andy McCall ↶ 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;
2bbe88a8 Andy McCall ↶ 14
use target::{Choice, Config, Target};
5c6e92fd Andy McCall ↶ 15
16
#[derive(Parser)]
e9bfea8e Andy McCall ↶ 17
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs and releases")]
5c6e92fd Andy McCall ↶ 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
    },
2291f8cc Andy McCall ↶ 70
    /// The repository's labels
71
    Label {
72
        #[command(subcommand)]
73
        cmd: LabelCmd,
74
    },
5ea4872f Andy McCall ↶ 75
    /// Milestones: list, create, edit, close
76
    Milestone {
77
        #[command(subcommand)]
78
        cmd: MilestoneCmd,
79
    },
17a3a84b Andy McCall ↶ 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
    },
62ceb2ee Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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 {
df71c789 Andy McCall ↶ 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
5c6e92fd Andy McCall ↶ 118
    Login {
df71c789 Andy McCall ↶ 119
        /// The hub, e.g. https://oxygenhub.io
5c6e92fd Andy McCall ↶ 120
        #[arg(long = "with-hub", value_name = "URL")]
121
        url: String,
df71c789 Andy McCall ↶ 122
        /// An API token from the hub's Settings → Tokens, instead of
123
        /// approving a code ("-" reads it from stdin)
5c6e92fd Andy McCall ↶ 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 {
2291f8cc Andy McCall ↶ 142
    /// Put labels on an issue or take them off (triage)
143
    Label(LabelChange),
5c6e92fd Andy McCall ↶ 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>,
17a3a84b Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 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 },
b5229b56 Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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 {
0b20f1ec Andy McCall ↶ 216
    /// Open proposals (or --state draft|landed|closed|all)
217
    List {
218
        #[arg(long, default_value = "open")]
219
        state: String,
220
    },
5c6e92fd Andy McCall ↶ 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>,
739a763a Andy McCall ↶ 229
        /// Read the body from a file ("-" for stdin)
230
        #[arg(long, short = 'F', conflicts_with = "body")]
231
        body_file: Option<String>,
5c6e92fd Andy McCall ↶ 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,
739a763a Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 251
    },
2291f8cc Andy McCall ↶ 252
    /// Put labels on a proposal or take them off (triage)
253
    Label(LabelChange),
739a763a Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 263
    /// The checks on a proposal's projected state
264
    Checks { number: i64 },
1f1eb06a Andy McCall ↶ 265
    /// Land a proposal on its target, as the page's Land button does
266
    Land { number: i64 },
62ceb2ee Andy McCall ↶ 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
    },
2291f8cc Andy McCall ↶ 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 },
17a3a84b Andy McCall ↶ 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 },
b1e92a62 Andy McCall ↶ 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
    },
17a3a84b Andy McCall ↶ 351
    /// Cards on a board: add, move, remove
352
    Card {
353
        #[command(subcommand)]
354
        cmd: CardCmd,
355
    },
2291f8cc Andy McCall ↶ 356
}
357
5ea4872f Andy McCall ↶ 358
#[derive(Subcommand)]
17a3a84b Andy McCall ↶ 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)]
5ea4872f Andy McCall ↶ 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
2291f8cc Andy McCall ↶ 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
    }
5c6e92fd Andy McCall ↶ 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 },
745d225d Andy McCall ↶ 477
    /// Cancel a run still queued or running; its running jobs are stopped
478
    Cancel { number: i64 },
5c6e92fd Andy McCall ↶ 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
    },
ced6d3af Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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() {
b5229b56 Andy McCall ↶ 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
    }
5c6e92fd Andy McCall ↶ 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),
2291f8cc Andy McCall ↶ 597
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
5ea4872f Andy McCall ↶ 598
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
17a3a84b Andy McCall ↶ 599
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
62ceb2ee Andy McCall ↶ 600
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
5c6e92fd Andy McCall ↶ 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();
df71c789 Andy McCall ↶ 606
    let token = match token.as_deref() {
607
        Some("-") => {
5c6e92fd Andy McCall ↶ 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
        }
df71c789 Andy McCall ↶ 613
        Some(t) => t.to_string(),
614
        None => device_sign_in(&hub, ca.clone())?,
5c6e92fd Andy McCall ↶ 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")?;
2bbe88a8 Andy McCall ↶ 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}"))?;
5c6e92fd Andy McCall ↶ 626
    cfg.default_hub = Some(hub.clone());
627
    cfg.save()?;
2bbe88a8 Andy McCall ↶ 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"));
5c6e92fd Andy McCall ↶ 630
    Ok(0)
631
}
632
df71c789 Andy McCall ↶ 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
5c6e92fd Andy McCall ↶ 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
        }
17a3a84b Andy McCall ↶ 739
        IssueCmd::Create { title, body, body_file, label, project, column } => {
5c6e92fd Andy McCall ↶ 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));
17a3a84b Andy McCall ↶ 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
                }
5c6e92fd Andy McCall ↶ 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);
b5229b56 Andy McCall ↶ 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
            }
2291f8cc Andy McCall ↶ 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
            }
5c6e92fd Andy McCall ↶ 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 {
0b20f1ec Andy McCall ↶ 842
        ProposalCmd::List { state } => {
843
            let path = format!("{base}/proposals?state={state}");
5c6e92fd Andy McCall ↶ 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() {
0b20f1ec Andy McCall ↶ 850
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
5c6e92fd Andy McCall ↶ 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
        }
739a763a Andy McCall ↶ 884
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
5c6e92fd Andy McCall ↶ 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
            };
739a763a Andy McCall ↶ 889
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
5c6e92fd Andy McCall ↶ 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));
1f1eb06a Andy McCall ↶ 895
            }
739a763a Andy McCall ↶ 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
            }
2291f8cc Andy McCall ↶ 905
            let edit = hub_api::ProposalEdit { title, body, labels: None };
739a763a Andy McCall ↶ 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));
2291f8cc Andy McCall ↶ 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));
739a763a Andy McCall ↶ 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("✔"));
1f1eb06a Andy McCall ↶ 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);
5c6e92fd Andy McCall ↶ 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}")));
67040b15 Andy McCall ↶ 980
        // Why a queued job no runner can take waits (oxygenhub#28).
981
        if j.status == "queued" && !j.waiting.is_empty() {
982
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
983
        }
5c6e92fd Andy McCall ↶ 984
    }
985
    if !r.error.is_empty() {
986
        println!("{}", ui::bad(&r.error));
987
    }
988
    println!("{}", ui::dim(&r.url));
989
}
990
991
fn live(status: &str) -> bool {
992
    matches!(status, "queued" | "running")
993
}
994
995
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
996
    let path = format!("{base}/flow/runs/{number}");
997
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
998
    loop {
999
        let r: FlowRun = c.get(&path)?;
1000
        if !json {
1001
            for j in &r.jobs {
67040b15 Andy McCall ↶ 1002
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1003
                if seen.get(&j.name) != Some(&shown) {
5c6e92fd Andy McCall ↶ 1004
                    println!("{} {}", ui::status(&j.status), j.name);
67040b15 Andy McCall ↶ 1005
                    if j.status == "queued" && !j.waiting.is_empty() {
1006
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1007
                    }
1008
                    seen.insert(j.name.clone(), shown);
5c6e92fd Andy McCall ↶ 1009
                }
1010
            }
1011
        }
1012
        if !live(&r.status) {
1013
            if json {
1014
                println!("{}", serde_json::to_string(&r)?);
1015
            } else {
1016
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1017
            }
1018
            return Ok(if r.status == "passed" { 0 } else { 1 });
1019
        }
1020
        std::thread::sleep(Duration::from_secs(3));
1021
    }
1022
}
1023
1024
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1025
    let base = t.repo_path()?;
1026
    match cmd {
1027
        RunCmd::List { limit } => {
1028
            let path = format!("{base}/flow/runs?limit={limit}");
1029
            if json {
1030
                println!("{}", c.get_text(&path)?);
1031
                return Ok(0);
1032
            }
1033
            let runs: Vec<FlowRun> = c.get(&path)?;
1034
            if runs.is_empty() {
1035
                println!("{}", ui::dim("No runs yet."));
1036
            }
1037
            for r in &runs {
1038
                println!("{}", run_line(r));
1039
            }
1040
        }
1041
        RunCmd::View { number } => {
1042
            let path = format!("{base}/flow/runs/{number}");
1043
            if json {
1044
                println!("{}", c.get_text(&path)?);
1045
                return Ok(0);
1046
            }
1047
            print_run(&c.get(&path)?);
1048
        }
1049
        RunCmd::Start { bookmark, change, watch: follow } => {
1050
            let body = match (bookmark, change) {
1051
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1052
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1053
                (None, None) => serde_json::json!({}),
1054
            };
1055
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1056
            let n = started["number"].as_i64().context("the hub named no run")?;
1057
            if !json || !follow {
1058
                if json {
1059
                    println!("{started}");
1060
                } else {
1061
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1062
                }
1063
            }
1064
            if follow {
1065
                return watch(c, &base, n, json);
1066
            }
1067
        }
1068
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1069
        RunCmd::Log { number, job } => {
1070
            let mut after = 0;
1071
            loop {
1072
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1073
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1074
                if lines.is_empty() {
1075
                    break;
1076
                }
1077
                for l in &lines {
1078
                    if json {
1079
                        println!("{}", serde_json::to_string(l)?);
1080
                    } else if l.stream == "flow" {
1081
                        println!("{}", ui::dim(&l.text));
1082
                    } else {
1083
                        println!("{}", l.text);
1084
                    }
1085
                }
1086
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1087
            }
1088
        }
1089
        RunCmd::Rerun { number } => {
1090
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1091
            if json {
1092
                println!("{started}");
1093
            } else {
1094
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
2291f8cc Andy McCall ↶ 1095
            }
1096
        }
745d225d Andy McCall ↶ 1097
        RunCmd::Cancel { number } => {
1098
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
1099
            if json {
1100
                println!("{done}");
1101
            } else {
1102
                println!("{} cancelled run #{number}", ui::ok("✔"));
1103
            }
1104
        }
2291f8cc Andy McCall ↶ 1105
    }
1106
    Ok(0)
1107
}
1108
1109
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
1110
    let base = t.repo_path()?;
1111
    match cmd {
1112
        LabelCmd::List => {
1113
            let path = format!("{base}/labels");
1114
            if json {
1115
                println!("{}", c.get_text(&path)?);
1116
                return Ok(0);
1117
            }
1118
            let labels: Vec<hub_api::Label> = c.get(&path)?;
1119
            if labels.is_empty() {
1120
                println!("{}", ui::dim("No labels."));
5c6e92fd Andy McCall ↶ 1121
            }
2291f8cc Andy McCall ↶ 1122
            for l in labels {
1123
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
1124
            }
1125
        }
1126
        LabelCmd::Create { name, colour, description } => {
1127
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
1128
            if json {
1129
                println!("{}", serde_json::to_string(&l)?);
1130
            } else {
1131
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
1132
            }
1133
        }
1134
        LabelCmd::Delete { name } => {
1135
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
1136
            println!("{} deleted label {name}", ui::ok("✔"));
62ceb2ee Andy McCall ↶ 1137
        }
1138
    }
1139
    Ok(0)
1140
}
1141
1142
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
1143
    let base = match (&org, site) {
1144
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
1145
        (None, true) => "/admin/assistants".to_string(),
1146
        (None, false) => format!("{}/assistants", t.repo_path()?),
1147
    };
1148
    match cmd {
1149
        AssistantCmd::List => {
1150
            if json {
1151
                println!("{}", c.get_text(&base)?);
1152
                return Ok(0);
1153
            }
1154
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
1155
            if list.is_empty() {
1156
                println!("{}", ui::dim("No assistants."));
1157
            }
1158
            for a in list {
1159
                let state = if a.enabled && !a.off_above {
1160
                    ui::ok("on")
1161
                } else if a.off_above {
1162
                    ui::dim("off above")
1163
                } else {
1164
                    ui::dim("off")
1165
                };
1166
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
1167
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1168
            }
1169
        }
1170
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
1171
            let token = match token_env {
1172
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
1173
                None => String::new(),
1174
            };
1175
            let body =
1176
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
1177
            let r: serde_json::Value = c.send("POST", &base, &body)?;
1178
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1179
        }
1180
        AssistantCmd::Remove { name } => {
1181
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
1182
            println!("{} removed {name}", ui::ok("✔"));
1183
        }
1184
        AssistantCmd::Prompt { set } => {
1185
            let p: hub_api::AssistantPrompt = match set {
1186
                Some(path) => {
1187
                    let text = if path.as_os_str() == "-" {
1188
                        let mut s = String::new();
1189
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1190
                        s
1191
                    } else {
1192
                        std::fs::read_to_string(&path)?
1193
                    };
1194
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1195
                }
1196
                None => c.get(&format!("{base}/prompt"))?,
1197
            };
1198
            if json {
1199
                println!("{}", serde_json::to_string(&p)?);
1200
                return Ok(0);
1201
            }
1202
            for (from, text) in &p.inherited {
1203
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
1204
            }
1205
            if p.prompt.is_empty() {
1206
                println!("{}", ui::dim("No prompt of its own."));
1207
            } else {
1208
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
1209
            }
17a3a84b Andy McCall ↶ 1210
        }
1211
    }
1212
    Ok(0)
1213
}
1214
1215
fn project_line(p: &hub_api::Project) -> String {
1216
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
1217
    let private = if p.public { "" } else { " · private" };
1218
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
1219
}
1220
1221
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
1222
    let owner = match owner {
1223
        Some(o) => o,
1224
        None => t.repo()?.0.to_string(),
1225
    };
1226
    let base = format!("/projects/{}", enc(&owner));
1227
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
1228
        let p: hub_api::Project =
1229
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
1230
        if json {
1231
            println!("{}", serde_json::to_string(&p)?);
1232
        } else {
1233
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
1234
        }
1235
        Ok(())
1236
    };
1237
    match cmd {
1238
        ProjectCmd::List => {
1239
            if json {
1240
                println!("{}", c.get_text(&base)?);
1241
                return Ok(0);
1242
            }
1243
            let list: Vec<hub_api::Project> = c.get(&base)?;
1244
            if list.is_empty() {
1245
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
1246
            }
1247
            for p in &list {
1248
                println!("{}", project_line(p));
1249
            }
1250
        }
1251
        ProjectCmd::View { number } => {
1252
            let path = format!("{base}/{number}");
1253
            if json {
1254
                println!("{}", c.get_text(&path)?);
1255
                return Ok(0);
1256
            }
1257
            let b: hub_api::Board = c.get(&path)?;
1258
            println!("{}", project_line(&b.project));
1259
            if !b.project.description.is_empty() {
1260
                println!("{}", b.project.description);
1261
            }
1262
            for col in &b.columns {
1263
                println!();
1264
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
1265
                if col.cards.is_empty() {
1266
                    println!("  {}", ui::dim("(empty)"));
1267
                }
1268
                for card in &col.cards {
1269
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
1270
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
1271
                    println!("  {} {what}{st}  {}", ui::dim(&format!("{:>4}", card.id)), card.title);
1272
                }
1273
            }
1274
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1275
        }
1276
        ProjectCmd::Create { title, description, private } => {
1277
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
1278
            if json {
1279
                println!("{}", serde_json::to_string(&p)?);
1280
            } else {
1281
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
1282
            }
1283
        }
1284
        ProjectCmd::Close { number } => state(number, true, "closed")?,
1285
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
b1e92a62 Andy McCall ↶ 1286
        ProjectCmd::Transfer { number, to } => {
1287
            let p: hub_api::Project =
1288
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
1289
            if json {
1290
                println!("{}", serde_json::to_string(&p)?);
1291
            } else {
1292
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
1293
            }
1294
        }
17a3a84b Andy McCall ↶ 1295
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1296
            // The hub names a card's issue as `repo#N` among the owner's
1297
            // repositories.
1298
            let reference = match reference {
1299
                None => String::new(),
1300
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
1301
                    Some((o, rest)) if o == owner => rest.to_string(),
1302
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
1303
                    None => r,
1304
                },
1305
                Some(r) => {
1306
                    let n = r.trim_start_matches('#');
1307
                    if n.parse::<i64>().is_err() {
1308
                        bail!("{r}: give an issue or proposal number, or NAME#N");
1309
                    }
1310
                    format!("{}#{n}", t.repo()?.1)
1311
                }
1312
            };
1313
            let note = note.unwrap_or_default();
1314
            if reference.is_empty() && note.is_empty() {
1315
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
1316
            }
1317
            let card: hub_api::ProjectCard =
1318
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
1319
            if json {
1320
                println!("{}", serde_json::to_string(&card)?);
1321
            } else {
1322
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
1323
            }
1324
        }
1325
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column } } => {
1326
            c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
1327
            println!("{} card {card} moved to {column}", ui::ok("✔"));
1328
        }
1329
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
1330
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
1331
            println!("{} card {card} removed", ui::ok("✔"));
5ea4872f Andy McCall ↶ 1332
        }
1333
    }
1334
    Ok(0)
1335
}
1336
1337
fn milestone_line(m: &hub_api::Milestone) -> String {
1338
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
1339
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
1340
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
1341
}
1342
1343
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
1344
    let base = t.repo_path()?;
1345
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
1346
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
1347
        if json {
1348
            println!("{}", serde_json::to_string(&m)?);
1349
        } else {
1350
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
1351
        }
1352
        Ok(())
1353
    };
1354
    match cmd {
1355
        MilestoneCmd::List => {
1356
            let path = format!("{base}/milestones");
1357
            if json {
1358
                println!("{}", c.get_text(&path)?);
1359
                return Ok(0);
1360
            }
1361
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
1362
            if list.is_empty() {
1363
                println!("{}", ui::dim("No milestones."));
1364
            }
1365
            for m in &list {
1366
                println!("{}", milestone_line(m));
1367
            }
1368
        }
1369
        MilestoneCmd::Create { title, description, due } => {
1370
            let m: hub_api::Milestone =
1371
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
1372
            if json {
1373
                println!("{}", serde_json::to_string(&m)?);
1374
            } else {
1375
                println!("{} milestone {}", ui::ok("✔"), m.title);
1376
            }
1377
        }
1378
        MilestoneCmd::Edit { title, rename, description, due } => {
1379
            if rename.is_none() && description.is_none() && due.is_none() {
1380
                bail!("say what to change: --rename, --description or --due");
1381
            }
1382
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1383
        }
1384
        MilestoneCmd::Close { title } => {
1385
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1386
        }
1387
        MilestoneCmd::Reopen { title } => {
1388
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
5c6e92fd Andy McCall ↶ 1389
        }
1390
    }
1391
    Ok(0)
1392
}
1393
1394
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
1395
    let base = t.repo_path()?;
1396
    match cmd {
1397
        ReleaseCmd::List => {
1398
            let path = format!("{base}/releases");
1399
            if json {
1400
                println!("{}", c.get_text(&path)?);
1401
                return Ok(0);
1402
            }
1403
            let list: Vec<Release> = c.get(&path)?;
1404
            if list.is_empty() {
1405
                println!("{}", ui::dim("No releases."));
1406
            }
1407
            for r in &list {
1408
                println!(
1409
                    "{} {} {}{}",
1410
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
1411
                    ui::strong(&r.tag),
1412
                    r.title,
1413
                    ui::dim(&format!(
1414
                        " · {} asset{} · {}",
1415
                        r.assets.len(),
1416
                        if r.assets.len() == 1 { "" } else { "s" },
1417
                        ui::ago(r.created_ms)
1418
                    ))
1419
                );
1420
            }
1421
        }
1422
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
1423
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
1424
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
1425
            if json {
1426
                println!("{}", serde_json::to_string(&r)?);
1427
            } else {
1428
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
ced6d3af Andy McCall ↶ 1429
            }
1430
        }
1431
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
1432
            let notes = match notes.as_deref() {
1433
                Some("-") => Some(body_of(None, Some("-".into()))?),
1434
                _ => notes,
1435
            };
1436
            if title.is_none() && notes.is_none() && prerelease.is_none() {
1437
                bail!("say what to change: --title, --notes or --prerelease");
1438
            }
1439
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
1440
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
1441
            if json {
1442
                println!("{}", serde_json::to_string(&r)?);
1443
            } else {
1444
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
5c6e92fd Andy McCall ↶ 1445
            }
1446
        }
1447
        ReleaseCmd::Upload { tag, files } => {
1448
            if files.is_empty() {
1449
                bail!("name the files to attach");
1450
            }
1451
            for f in files {
1452
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
1453
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
1454
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
1455
                println!("{} attached {name} to {tag}", ui::ok("✔"));
1456
            }
1457
        }
1458
        ReleaseCmd::Trust { tag } => {
1459
            let path = format!("{base}/releases/trust/{}", enc(&tag));
1460
            if json {
1461
                println!("{}", c.get_text(&path)?);
1462
                return Ok(0);
1463
            }
1464
            let r: serde_json::Value = c.get(&path)?;
1465
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
1466
            let mut worst = 0;
1467
            for ch in r["audit"].as_array().into_iter().flatten() {
1468
                let v = ch["verdict"].as_str().unwrap_or("");
1469
                worst = worst.max(match v {
1470
                    "fail" => 2,
1471
                    "warn" => 1,
1472
                    _ => 0,
1473
                });
1474
                let g = match v {
1475
                    "pass" => ui::ok("✔"),
1476
                    "warn" => ui::warn("!"),
1477
                    _ => ui::bad("✘"),
1478
                };
1479
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
1480
            }
1481
            return Ok(if worst == 2 { 1 } else { 0 });
1482
        }
1483
    }
1484
    Ok(0)
1485
}