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