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