| 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, Tag}; |
| 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, releases and drops")] |
| 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 |
Coverage { |
| 62 |
#[command(subcommand)] |
| 63 |
cmd: CoverageCmd, |
| 64 |
}, |
| 65 |
|
| 66 |
Run { |
| 67 |
#[command(subcommand)] |
| 68 |
cmd: RunCmd, |
| 69 |
}, |
| 70 |
|
| 71 |
Release { |
| 72 |
#[command(subcommand)] |
| 73 |
cmd: ReleaseCmd, |
| 74 |
}, |
| 75 |
|
| 76 |
Tag { |
| 77 |
#[command(subcommand)] |
| 78 |
cmd: TagCmd, |
| 79 |
}, |
| 80 |
|
| 81 |
Label { |
| 82 |
#[command(subcommand)] |
| 83 |
cmd: LabelCmd, |
| 84 |
}, |
| 85 |
|
| 86 |
Milestone { |
| 87 |
#[command(subcommand)] |
| 88 |
cmd: MilestoneCmd, |
| 89 |
}, |
| 90 |
|
| 91 |
|
| 92 |
Project { |
| 93 |
#[command(subcommand)] |
| 94 |
cmd: ProjectCmd, |
| 95 |
|
| 96 |
#[arg(long, global = true)] |
| 97 |
owner: Option<String>, |
| 98 |
}, |
| 99 |
|
| 100 |
|
| 101 |
Assistant { |
| 102 |
#[command(subcommand)] |
| 103 |
cmd: AssistantCmd, |
| 104 |
|
| 105 |
#[arg(long, global = true)] |
| 106 |
org: Option<String>, |
| 107 |
|
| 108 |
#[arg(long, global = true, conflicts_with = "org")] |
| 109 |
site: bool, |
| 110 |
}, |
| 111 |
|
| 112 |
|
| 113 |
Agent { |
| 114 |
#[command(subcommand)] |
| 115 |
cmd: AgentCmd, |
| 116 |
}, |
| 117 |
|
| 118 |
|
| 119 |
Drop { |
| 120 |
#[command(subcommand)] |
| 121 |
cmd: DropCmd, |
| 122 |
}, |
| 123 |
|
| 124 |
|
| 125 |
#[command(name = "runner-updates")] |
| 126 |
RunnerUpdates { |
| 127 |
#[command(subcommand)] |
| 128 |
cmd: Option<RunnerUpdatesCmd>, |
| 129 |
}, |
| 130 |
|
| 131 |
Api { |
| 132 |
|
| 133 |
path: String, |
| 134 |
|
| 135 |
#[arg(long, short = 'X', default_value = "GET")] |
| 136 |
method: String, |
| 137 |
|
| 138 |
#[arg(long, short = 'd')] |
| 139 |
data: Option<String>, |
| 140 |
}, |
| 141 |
} |
| 142 |
|
| 143 |
#[derive(Subcommand)] |
| 144 |
enum AgentCmd { |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
Grant { |
| 150 |
|
| 151 |
name: String, |
| 152 |
|
| 153 |
#[arg(long, default_value = "changes,seal,refs")] |
| 154 |
scope: String, |
| 155 |
|
| 156 |
#[arg(long = "for", value_name = "DURATION", default_value = "30d")] |
| 157 |
lasts: String, |
| 158 |
}, |
| 159 |
|
| 160 |
List, |
| 161 |
|
| 162 |
Revoke { id: i64 }, |
| 163 |
} |
| 164 |
|
| 165 |
#[derive(Subcommand)] |
| 166 |
enum DropCmd { |
| 167 |
|
| 168 |
Create { |
| 169 |
|
| 170 |
#[arg(required = true)] |
| 171 |
files: Vec<std::path::PathBuf>, |
| 172 |
|
| 173 |
#[arg(long)] |
| 174 |
secret: bool, |
| 175 |
|
| 176 |
#[arg(long, short = 'd', value_name = "TEXT")] |
| 177 |
description: Option<String>, |
| 178 |
|
| 179 |
#[arg(long, short = 't')] |
| 180 |
title: Option<String>, |
| 181 |
}, |
| 182 |
|
| 183 |
List { |
| 184 |
|
| 185 |
#[arg(long, short = 'u', value_name = "NAME")] |
| 186 |
user: Option<String>, |
| 187 |
}, |
| 188 |
|
| 189 |
View { |
| 190 |
|
| 191 |
id: String, |
| 192 |
|
| 193 |
#[arg(long, short = 'f', value_name = "NAME")] |
| 194 |
file: Option<String>, |
| 195 |
}, |
| 196 |
|
| 197 |
Delete { |
| 198 |
|
| 199 |
id: String, |
| 200 |
}, |
| 201 |
} |
| 202 |
|
| 203 |
#[derive(Subcommand)] |
| 204 |
enum RunnerUpdatesCmd { |
| 205 |
|
| 206 |
Show, |
| 207 |
|
| 208 |
Set { |
| 209 |
|
| 210 |
scope: String, |
| 211 |
|
| 212 |
#[arg(long)] |
| 213 |
updates: Option<String>, |
| 214 |
|
| 215 |
#[arg(long)] |
| 216 |
channel: Option<String>, |
| 217 |
|
| 218 |
#[arg(long)] |
| 219 |
window: Option<String>, |
| 220 |
|
| 221 |
#[arg(long)] |
| 222 |
dry_run: Option<String>, |
| 223 |
}, |
| 224 |
|
| 225 |
Lift { version: String }, |
| 226 |
} |
| 227 |
|
| 228 |
#[derive(Subcommand)] |
| 229 |
enum AuthCmd { |
| 230 |
|
| 231 |
|
| 232 |
Login { |
| 233 |
|
| 234 |
#[arg(long = "with-hub", value_name = "URL")] |
| 235 |
url: String, |
| 236 |
|
| 237 |
|
| 238 |
#[arg(long)] |
| 239 |
token: Option<String>, |
| 240 |
|
| 241 |
#[arg(long)] |
| 242 |
ca: Option<std::path::PathBuf>, |
| 243 |
}, |
| 244 |
|
| 245 |
Status, |
| 246 |
} |
| 247 |
|
| 248 |
#[derive(Subcommand)] |
| 249 |
enum RepoCmd { |
| 250 |
|
| 251 |
View, |
| 252 |
} |
| 253 |
|
| 254 |
#[derive(Subcommand)] |
| 255 |
enum IssueCmd { |
| 256 |
|
| 257 |
Label(LabelChange), |
| 258 |
|
| 259 |
List { |
| 260 |
#[arg(long, default_value = "open")] |
| 261 |
state: String, |
| 262 |
}, |
| 263 |
|
| 264 |
View { number: i64 }, |
| 265 |
|
| 266 |
Create { |
| 267 |
#[arg(long, short)] |
| 268 |
title: String, |
| 269 |
#[arg(long, short)] |
| 270 |
body: Option<String>, |
| 271 |
|
| 272 |
#[arg(long, short = 'F')] |
| 273 |
body_file: Option<String>, |
| 274 |
|
| 275 |
#[arg(long, short)] |
| 276 |
label: Vec<String>, |
| 277 |
|
| 278 |
#[arg(long, short)] |
| 279 |
project: Option<i64>, |
| 280 |
|
| 281 |
#[arg(long, requires = "project")] |
| 282 |
column: Option<String>, |
| 283 |
}, |
| 284 |
|
| 285 |
Close { |
| 286 |
number: i64, |
| 287 |
|
| 288 |
#[arg(long, default_value = "completed")] |
| 289 |
reason: String, |
| 290 |
}, |
| 291 |
|
| 292 |
Reopen { number: i64 }, |
| 293 |
|
| 294 |
|
| 295 |
Edit { |
| 296 |
number: i64, |
| 297 |
#[arg(long, short)] |
| 298 |
title: Option<String>, |
| 299 |
#[arg(long, short)] |
| 300 |
body: Option<String>, |
| 301 |
|
| 302 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 303 |
body_file: Option<String>, |
| 304 |
|
| 305 |
#[arg(long, short)] |
| 306 |
label: Vec<String>, |
| 307 |
|
| 308 |
#[arg(long, conflicts_with = "label")] |
| 309 |
no_labels: bool, |
| 310 |
|
| 311 |
#[arg(long, short)] |
| 312 |
assignee: Vec<String>, |
| 313 |
|
| 314 |
#[arg(long, conflicts_with = "assignee")] |
| 315 |
no_assignees: bool, |
| 316 |
|
| 317 |
#[arg(long, short)] |
| 318 |
milestone: Option<String>, |
| 319 |
}, |
| 320 |
|
| 321 |
Comment { |
| 322 |
number: i64, |
| 323 |
#[arg(long, short)] |
| 324 |
body: String, |
| 325 |
}, |
| 326 |
} |
| 327 |
|
| 328 |
#[derive(Subcommand)] |
| 329 |
enum ProposalCmd { |
| 330 |
|
| 331 |
List { |
| 332 |
#[arg(long, default_value = "open")] |
| 333 |
state: String, |
| 334 |
}, |
| 335 |
|
| 336 |
View { number: i64 }, |
| 337 |
|
| 338 |
Create { |
| 339 |
#[arg(long, short)] |
| 340 |
title: String, |
| 341 |
#[arg(long, short)] |
| 342 |
body: Option<String>, |
| 343 |
|
| 344 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 345 |
body_file: Option<String>, |
| 346 |
|
| 347 |
#[arg(long)] |
| 348 |
from: String, |
| 349 |
|
| 350 |
#[arg(long)] |
| 351 |
into: Option<String>, |
| 352 |
#[arg(long)] |
| 353 |
draft: bool, |
| 354 |
}, |
| 355 |
|
| 356 |
Edit { |
| 357 |
number: i64, |
| 358 |
#[arg(long, short)] |
| 359 |
title: Option<String>, |
| 360 |
#[arg(long, short)] |
| 361 |
body: Option<String>, |
| 362 |
|
| 363 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 364 |
body_file: Option<String>, |
| 365 |
}, |
| 366 |
|
| 367 |
Label(LabelChange), |
| 368 |
|
| 369 |
Comment { |
| 370 |
number: i64, |
| 371 |
#[arg(long, short)] |
| 372 |
body: Option<String>, |
| 373 |
|
| 374 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 375 |
body_file: Option<String>, |
| 376 |
}, |
| 377 |
|
| 378 |
Checks { number: i64 }, |
| 379 |
|
| 380 |
Land { |
| 381 |
number: i64, |
| 382 |
|
| 383 |
|
| 384 |
#[arg(long, value_name = "REASON", conflicts_with = "when_ready")] |
| 385 |
over_checks: Option<String>, |
| 386 |
|
| 387 |
#[arg(long)] |
| 388 |
when_ready: bool, |
| 389 |
|
| 390 |
#[arg(long, requires = "when_ready")] |
| 391 |
off: bool, |
| 392 |
}, |
| 393 |
|
| 394 |
Close { |
| 395 |
number: i64, |
| 396 |
|
| 397 |
#[arg(long, short = 'm')] |
| 398 |
message: Option<String>, |
| 399 |
}, |
| 400 |
|
| 401 |
Reopen { number: i64 }, |
| 402 |
|
| 403 |
Ready { |
| 404 |
number: i64, |
| 405 |
|
| 406 |
#[arg(long)] |
| 407 |
undo: bool, |
| 408 |
}, |
| 409 |
} |
| 410 |
|
| 411 |
#[derive(Subcommand)] |
| 412 |
enum AssistantCmd { |
| 413 |
|
| 414 |
List, |
| 415 |
|
| 416 |
Add { |
| 417 |
|
| 418 |
#[arg(long, default_value = "")] |
| 419 |
name: String, |
| 420 |
|
| 421 |
#[arg(long, default_value = "")] |
| 422 |
preset: String, |
| 423 |
|
| 424 |
#[arg(long, default_value = "")] |
| 425 |
endpoint: String, |
| 426 |
|
| 427 |
#[arg(long, default_value = "")] |
| 428 |
api: String, |
| 429 |
|
| 430 |
#[arg(long)] |
| 431 |
model: String, |
| 432 |
|
| 433 |
#[arg(long, value_name = "VAR")] |
| 434 |
token_env: Option<String>, |
| 435 |
|
| 436 |
#[arg(long)] |
| 437 |
off: bool, |
| 438 |
}, |
| 439 |
|
| 440 |
Remove { name: String }, |
| 441 |
|
| 442 |
Prompt { |
| 443 |
|
| 444 |
#[arg(long, value_name = "FILE")] |
| 445 |
set: Option<std::path::PathBuf>, |
| 446 |
}, |
| 447 |
} |
| 448 |
|
| 449 |
#[derive(Subcommand)] |
| 450 |
enum LabelCmd { |
| 451 |
|
| 452 |
List, |
| 453 |
|
| 454 |
Create { |
| 455 |
name: String, |
| 456 |
|
| 457 |
#[arg(long)] |
| 458 |
colour: Option<String>, |
| 459 |
#[arg(long, short, default_value = "")] |
| 460 |
description: String, |
| 461 |
}, |
| 462 |
|
| 463 |
Delete { name: String }, |
| 464 |
} |
| 465 |
|
| 466 |
#[derive(Subcommand)] |
| 467 |
enum ProjectCmd { |
| 468 |
|
| 469 |
List, |
| 470 |
|
| 471 |
View { |
| 472 |
number: i64, |
| 473 |
|
| 474 |
#[arg(long)] |
| 475 |
archived: bool, |
| 476 |
}, |
| 477 |
|
| 478 |
Create { |
| 479 |
title: String, |
| 480 |
#[arg(long, short, default_value = "")] |
| 481 |
description: String, |
| 482 |
|
| 483 |
#[arg(long)] |
| 484 |
private: bool, |
| 485 |
}, |
| 486 |
|
| 487 |
Close { number: i64 }, |
| 488 |
|
| 489 |
Reopen { number: i64 }, |
| 490 |
|
| 491 |
|
| 492 |
Transfer { |
| 493 |
number: i64, |
| 494 |
|
| 495 |
#[arg(long)] |
| 496 |
to: String, |
| 497 |
}, |
| 498 |
|
| 499 |
Card { |
| 500 |
#[command(subcommand)] |
| 501 |
cmd: CardCmd, |
| 502 |
}, |
| 503 |
} |
| 504 |
|
| 505 |
#[derive(Subcommand)] |
| 506 |
enum CardCmd { |
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
Add { |
| 511 |
number: i64, |
| 512 |
|
| 513 |
reference: Option<String>, |
| 514 |
|
| 515 |
#[arg(long, conflicts_with = "reference")] |
| 516 |
note: Option<String>, |
| 517 |
|
| 518 |
#[arg(long, short)] |
| 519 |
column: Option<String>, |
| 520 |
}, |
| 521 |
|
| 522 |
|
| 523 |
Move { |
| 524 |
number: i64, |
| 525 |
|
| 526 |
card: Option<i64>, |
| 527 |
#[arg(long, short)] |
| 528 |
column: String, |
| 529 |
|
| 530 |
#[arg(long, conflicts_with = "card")] |
| 531 |
from: Option<String>, |
| 532 |
|
| 533 |
#[arg(long, value_delimiter = ',', requires = "from")] |
| 534 |
except: Vec<String>, |
| 535 |
|
| 536 |
#[arg(long, value_delimiter = ',', requires = "from")] |
| 537 |
state: Vec<String>, |
| 538 |
|
| 539 |
#[arg(long, requires = "from")] |
| 540 |
dry_run: bool, |
| 541 |
}, |
| 542 |
|
| 543 |
Archive { |
| 544 |
number: i64, |
| 545 |
|
| 546 |
#[arg(long)] |
| 547 |
from: String, |
| 548 |
|
| 549 |
#[arg(long)] |
| 550 |
older: Option<String>, |
| 551 |
|
| 552 |
#[arg(long, value_delimiter = ',')] |
| 553 |
except: Vec<String>, |
| 554 |
|
| 555 |
#[arg(long, value_delimiter = ',')] |
| 556 |
state: Vec<String>, |
| 557 |
|
| 558 |
#[arg(long)] |
| 559 |
dry_run: bool, |
| 560 |
}, |
| 561 |
|
| 562 |
Restore { number: i64, card: i64 }, |
| 563 |
|
| 564 |
Remove { number: i64, card: i64 }, |
| 565 |
} |
| 566 |
|
| 567 |
#[derive(Subcommand)] |
| 568 |
enum MilestoneCmd { |
| 569 |
|
| 570 |
List, |
| 571 |
|
| 572 |
Create { |
| 573 |
title: String, |
| 574 |
#[arg(long, short, default_value = "")] |
| 575 |
description: String, |
| 576 |
|
| 577 |
#[arg(long)] |
| 578 |
due: Option<String>, |
| 579 |
}, |
| 580 |
|
| 581 |
Edit { |
| 582 |
title: String, |
| 583 |
#[arg(long, short)] |
| 584 |
rename: Option<String>, |
| 585 |
#[arg(long, short)] |
| 586 |
description: Option<String>, |
| 587 |
|
| 588 |
#[arg(long)] |
| 589 |
due: Option<String>, |
| 590 |
}, |
| 591 |
|
| 592 |
Close { title: String }, |
| 593 |
|
| 594 |
Reopen { title: String }, |
| 595 |
} |
| 596 |
|
| 597 |
|
| 598 |
#[derive(clap::Args)] |
| 599 |
struct LabelChange { |
| 600 |
number: i64, |
| 601 |
|
| 602 |
#[arg(long, short)] |
| 603 |
add: Vec<String>, |
| 604 |
|
| 605 |
#[arg(long, short)] |
| 606 |
remove: Vec<String>, |
| 607 |
} |
| 608 |
|
| 609 |
impl LabelChange { |
| 610 |
|
| 611 |
fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> { |
| 612 |
if self.add.is_empty() && self.remove.is_empty() { |
| 613 |
bail!("say what to change: --add NAME or --remove NAME"); |
| 614 |
} |
| 615 |
let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect(); |
| 616 |
for a in &self.add { |
| 617 |
if !names.contains(a) { |
| 618 |
names.push(a.clone()); |
| 619 |
} |
| 620 |
} |
| 621 |
Ok(names) |
| 622 |
} |
| 623 |
} |
| 624 |
|
| 625 |
fn label_names(labels: &[String]) -> String { |
| 626 |
if labels.is_empty() { |
| 627 |
ui::dim("no labels") |
| 628 |
} else { |
| 629 |
labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ") |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
#[derive(Subcommand)] |
| 634 |
enum CoverageCmd { |
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
Upload { |
| 640 |
file: std::path::PathBuf, |
| 641 |
#[arg(long)] |
| 642 |
bookmark: Option<String>, |
| 643 |
|
| 644 |
#[arg(long, conflicts_with = "bookmark")] |
| 645 |
change: Option<String>, |
| 646 |
}, |
| 647 |
} |
| 648 |
|
| 649 |
#[derive(Subcommand)] |
| 650 |
enum RunCmd { |
| 651 |
|
| 652 |
List { |
| 653 |
#[arg(long, default_value_t = 20)] |
| 654 |
limit: i64, |
| 655 |
}, |
| 656 |
|
| 657 |
View { number: i64 }, |
| 658 |
|
| 659 |
Start { |
| 660 |
#[arg(long)] |
| 661 |
bookmark: Option<String>, |
| 662 |
|
| 663 |
#[arg(long, conflicts_with = "bookmark")] |
| 664 |
change: Option<String>, |
| 665 |
|
| 666 |
#[arg(long = "job", value_name = "NAME")] |
| 667 |
jobs: Vec<String>, |
| 668 |
|
| 669 |
#[arg(long)] |
| 670 |
watch: bool, |
| 671 |
}, |
| 672 |
|
| 673 |
Watch { number: i64 }, |
| 674 |
|
| 675 |
Log { number: i64, job: String }, |
| 676 |
|
| 677 |
|
| 678 |
Rerun { |
| 679 |
number: i64, |
| 680 |
#[arg(long)] |
| 681 |
job: Option<String>, |
| 682 |
}, |
| 683 |
|
| 684 |
Cancel { number: i64 }, |
| 685 |
|
| 686 |
Approve { |
| 687 |
number: i64, |
| 688 |
#[arg(long)] |
| 689 |
job: String, |
| 690 |
}, |
| 691 |
|
| 692 |
Reject { |
| 693 |
number: i64, |
| 694 |
#[arg(long)] |
| 695 |
job: String, |
| 696 |
}, |
| 697 |
} |
| 698 |
|
| 699 |
#[derive(Subcommand)] |
| 700 |
enum TagCmd { |
| 701 |
|
| 702 |
List, |
| 703 |
|
| 704 |
|
| 705 |
Create { |
| 706 |
name: String, |
| 707 |
|
| 708 |
#[arg(long)] |
| 709 |
target: Option<String>, |
| 710 |
#[arg(long, short)] |
| 711 |
message: Option<String>, |
| 712 |
}, |
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
Delete { |
| 717 |
name: String, |
| 718 |
|
| 719 |
#[arg(long, short)] |
| 720 |
reason: Option<String>, |
| 721 |
}, |
| 722 |
} |
| 723 |
|
| 724 |
#[derive(Subcommand)] |
| 725 |
enum ReleaseCmd { |
| 726 |
|
| 727 |
List, |
| 728 |
|
| 729 |
Create { |
| 730 |
tag: String, |
| 731 |
#[arg(long, short)] |
| 732 |
title: Option<String>, |
| 733 |
|
| 734 |
#[arg(long, short)] |
| 735 |
notes: Option<String>, |
| 736 |
#[arg(long)] |
| 737 |
prerelease: bool, |
| 738 |
}, |
| 739 |
|
| 740 |
Edit { |
| 741 |
tag: String, |
| 742 |
#[arg(long, short)] |
| 743 |
title: Option<String>, |
| 744 |
|
| 745 |
#[arg(long, short)] |
| 746 |
notes: Option<String>, |
| 747 |
|
| 748 |
#[arg(long)] |
| 749 |
prerelease: Option<bool>, |
| 750 |
}, |
| 751 |
|
| 752 |
Upload { tag: String, files: Vec<std::path::PathBuf> }, |
| 753 |
|
| 754 |
Trust { tag: String }, |
| 755 |
} |
| 756 |
|
| 757 |
fn main() { |
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
#[cfg(unix)] |
| 762 |
unsafe { |
| 763 |
libc::signal(libc::SIGPIPE, libc::SIG_DFL); |
| 764 |
} |
| 765 |
let cli = Cli::parse(); |
| 766 |
ui::init(cli.plain); |
| 767 |
match run(cli) { |
| 768 |
Ok(code) => std::process::exit(code), |
| 769 |
Err(e) => { |
| 770 |
eprintln!("{} {e:#}", ui::bad("error:")); |
| 771 |
std::process::exit(2); |
| 772 |
} |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
fn enc(s: &str) -> String { |
| 777 |
let mut out = String::new(); |
| 778 |
for b in s.bytes() { |
| 779 |
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { |
| 780 |
out.push(b as char); |
| 781 |
} else { |
| 782 |
out.push_str(&format!("%{b:02X}")); |
| 783 |
} |
| 784 |
} |
| 785 |
out |
| 786 |
} |
| 787 |
|
| 788 |
fn run(cli: Cli) -> Result<i32> { |
| 789 |
let cfg = Config::load()?; |
| 790 |
if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd { |
| 791 |
return login(cfg, url, token.clone(), ca.clone()); |
| 792 |
} |
| 793 |
let here = std::env::current_dir()?; |
| 794 |
let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?; |
| 795 |
let c = Client::new(&t)?; |
| 796 |
let json = cli.json; |
| 797 |
match cli.cmd { |
| 798 |
Cmd::Auth { cmd: AuthCmd::Status } => { |
| 799 |
let me: serde_json::Value = c.get("/user")?; |
| 800 |
if json { |
| 801 |
println!("{me}"); |
| 802 |
} else { |
| 803 |
println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?"))); |
| 804 |
} |
| 805 |
Ok(0) |
| 806 |
} |
| 807 |
Cmd::Auth { .. } => unreachable!(), |
| 808 |
Cmd::Api { path, method, data } => { |
| 809 |
let path = if path.starts_with('/') { path } else { format!("/{path}") }; |
| 810 |
let text = match data { |
| 811 |
Some(d) => c.send_text( |
| 812 |
&method.to_uppercase(), |
| 813 |
&path, |
| 814 |
&serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?, |
| 815 |
)?, |
| 816 |
None => c.get_text(&path)?, |
| 817 |
}; |
| 818 |
println!("{text}"); |
| 819 |
Ok(0) |
| 820 |
} |
| 821 |
Cmd::Repo { cmd: RepoCmd::View } => { |
| 822 |
let path = t.repo_path()?; |
| 823 |
if json { |
| 824 |
println!("{}", c.get_text(&path)?); |
| 825 |
return Ok(0); |
| 826 |
} |
| 827 |
let r: serde_json::Value = c.get(&path)?; |
| 828 |
println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or(""))); |
| 829 |
if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) { |
| 830 |
println!("{d}"); |
| 831 |
} |
| 832 |
println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or(""))); |
| 833 |
println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name))); |
| 834 |
Ok(0) |
| 835 |
} |
| 836 |
Cmd::Issue { cmd } => issue(&c, &t, cmd, json), |
| 837 |
Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json), |
| 838 |
Cmd::Run { cmd } => flow(&c, &t, cmd, json), |
| 839 |
Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => { |
| 840 |
let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?; |
| 841 |
let mut body = serde_json::json!({ "content": content }); |
| 842 |
if let Some(b) = bookmark { |
| 843 |
body["bookmark"] = b.into(); |
| 844 |
} |
| 845 |
if let Some(ch) = change { |
| 846 |
body["change"] = ch.into(); |
| 847 |
} |
| 848 |
let base = t.repo_path()?; |
| 849 |
let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?; |
| 850 |
if json { |
| 851 |
println!("{}", serde_json::to_string(&r)?); |
| 852 |
} else { |
| 853 |
let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into()); |
| 854 |
let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() }; |
| 855 |
println!( |
| 856 |
"{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}", |
| 857 |
ui::ok("✔"), |
| 858 |
r.lines_hit, |
| 859 |
r.lines_found, |
| 860 |
r.files, |
| 861 |
ui::dim(&r.url) |
| 862 |
); |
| 863 |
if r.dropped > 0 { |
| 864 |
println!(" {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped))); |
| 865 |
} |
| 866 |
} |
| 867 |
Ok(0) |
| 868 |
} |
| 869 |
Cmd::Release { cmd } => release(&c, &t, cmd, json), |
| 870 |
Cmd::Tag { cmd } => tag(&c, &t, cmd, json), |
| 871 |
Cmd::Label { cmd } => label(&c, &t, cmd, json), |
| 872 |
Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json), |
| 873 |
Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json), |
| 874 |
Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json), |
| 875 |
Cmd::Agent { cmd } => agent(&c, cmd, json), |
| 876 |
Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json), |
| 877 |
Cmd::Drop { cmd } => drop_cmd(&c, cmd, json), |
| 878 |
} |
| 879 |
} |
| 880 |
|
| 881 |
|
| 882 |
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> { |
| 883 |
Ok(match v { |
| 884 |
None => None, |
| 885 |
Some("on") => Some(Some(true)), |
| 886 |
Some("off") => Some(Some(false)), |
| 887 |
Some("inherit") => Some(None), |
| 888 |
Some(other) => bail!("{other:?}: say on, off or inherit"), |
| 889 |
}) |
| 890 |
} |
| 891 |
|
| 892 |
|
| 893 |
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> { |
| 894 |
let (kind, name) = scope.split_once(':').unwrap_or((scope, "")); |
| 895 |
Ok(match kind { |
| 896 |
"site" if name.is_empty() => ("site".into(), String::new()), |
| 897 |
"owner" if !name.is_empty() => ("owner".into(), name.into()), |
| 898 |
"group" => { |
| 899 |
let g = all |
| 900 |
.groups |
| 901 |
.iter() |
| 902 |
.find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name) |
| 903 |
.with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?; |
| 904 |
("group".into(), g.id.to_string()) |
| 905 |
} |
| 906 |
"runner" => { |
| 907 |
let r = all |
| 908 |
.runners |
| 909 |
.iter() |
| 910 |
.find(|r| r.id.to_string() == name || r.name == name) |
| 911 |
.with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?; |
| 912 |
("runner".into(), r.id.to_string()) |
| 913 |
} |
| 914 |
_ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"), |
| 915 |
}) |
| 916 |
} |
| 917 |
|
| 918 |
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> { |
| 919 |
let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?; |
| 920 |
match cmd { |
| 921 |
RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?), |
| 922 |
RunnerUpdatesCmd::Show => { |
| 923 |
println!( |
| 924 |
"{} {}", |
| 925 |
ui::strong("Builds from"), |
| 926 |
if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() } |
| 927 |
); |
| 928 |
for h in &all.holds { |
| 929 |
println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why); |
| 930 |
} |
| 931 |
for s in &all.settings { |
| 932 |
let mut said = vec![]; |
| 933 |
if let Some(u) = s.updates { |
| 934 |
said.push(format!("updates {}", if u { "on" } else { "off" })); |
| 935 |
} |
| 936 |
if let Some(ch) = &s.channel { |
| 937 |
said.push(format!("channel {ch}")); |
| 938 |
} |
| 939 |
if let Some(w) = &s.window { |
| 940 |
said.push(format!("window {w} UTC")); |
| 941 |
} |
| 942 |
if let Some(d) = s.dry_run { |
| 943 |
said.push(format!("dry run {}", if d { "on" } else { "off" })); |
| 944 |
} |
| 945 |
let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) }; |
| 946 |
println!(" {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") }); |
| 947 |
} |
| 948 |
for g in &all.groups { |
| 949 |
let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) }; |
| 950 |
let what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}")); |
| 951 |
println!( |
| 952 |
" group {} ({what}): {}", |
| 953 |
ui::strong(&g.name), |
| 954 |
if g.members.is_empty() { "none".into() } else { g.members.join(", ") } |
| 955 |
); |
| 956 |
} |
| 957 |
for r in &all.runners { |
| 958 |
let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") }; |
| 959 |
println!(" {:<16} flow {:<22} {} ({}) {}", r.name, r.version, on, r.from[0], ui::dim(&r.now)); |
| 960 |
} |
| 961 |
} |
| 962 |
RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => { |
| 963 |
let (scope, key) = update_scope(&scope, &all)?; |
| 964 |
let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting { |
| 965 |
scope: scope.clone(), |
| 966 |
key: key.clone(), |
| 967 |
..Default::default() |
| 968 |
}); |
| 969 |
if let Some(u) = switch(updates.as_deref())? { |
| 970 |
s.updates = u; |
| 971 |
} |
| 972 |
if let Some(d) = switch(dry_run.as_deref())? { |
| 973 |
s.dry_run = d; |
| 974 |
} |
| 975 |
if let Some(ch) = channel { |
| 976 |
s.channel = Some(ch).filter(|c| c != "inherit"); |
| 977 |
} |
| 978 |
if let Some(w) = window { |
| 979 |
s.window = Some(w).filter(|w| w != "inherit"); |
| 980 |
} |
| 981 |
let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?; |
| 982 |
println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved")); |
| 983 |
} |
| 984 |
RunnerUpdatesCmd::Lift { version } => { |
| 985 |
c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?; |
| 986 |
println!("{} flow {version} is offered again where the settings say so", ui::ok("✔")); |
| 987 |
} |
| 988 |
} |
| 989 |
Ok(0) |
| 990 |
} |
| 991 |
|
| 992 |
|
| 993 |
fn drop_id(s: &str) -> Result<String> { |
| 994 |
let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string(); |
| 995 |
if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 996 |
bail!("{s:?} is not a drop's id or address"); |
| 997 |
} |
| 998 |
Ok(id.to_ascii_lowercase()) |
| 999 |
} |
| 1000 |
|
| 1001 |
fn drop_line(d: &hub_api::Drop) -> String { |
| 1002 |
let title = if d.title.is_empty() { d.files.first().map(|f| f.name.clone()).unwrap_or_else(|| d.id.clone()) } else { d.title.clone() }; |
| 1003 |
let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect(); |
| 1004 |
format!( |
| 1005 |
"{} {} {}{}", |
| 1006 |
ui::dim(&d.id), |
| 1007 |
ui::strong(&title), |
| 1008 |
if d.visibility == "secret" { ui::warn("secret ") } else { String::new() }, |
| 1009 |
ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms))) |
| 1010 |
) |
| 1011 |
} |
| 1012 |
|
| 1013 |
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> { |
| 1014 |
match cmd { |
| 1015 |
DropCmd::Create { files, secret, description, title } => { |
| 1016 |
let mut out = Vec::with_capacity(files.len()); |
| 1017 |
for f in &files { |
| 1018 |
let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?; |
| 1019 |
let content = |
| 1020 |
std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?; |
| 1021 |
out.push(hub_api::NewDropFile { name: name.to_string(), content }); |
| 1022 |
} |
| 1023 |
let new = |
| 1024 |
hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out }; |
| 1025 |
let d: hub_api::Drop = c.send("POST", "/drops", &new)?; |
| 1026 |
if json { |
| 1027 |
println!("{}", serde_json::to_string(&d)?); |
| 1028 |
} else { |
| 1029 |
println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url)); |
| 1030 |
println!(" {}", ui::dim(&format!("oxy clone {}", d.clone_url))); |
| 1031 |
} |
| 1032 |
} |
| 1033 |
DropCmd::List { user } => { |
| 1034 |
let path = match &user { |
| 1035 |
Some(u) => format!("/users/{}/drops", enc(u)), |
| 1036 |
None => "/drops".to_string(), |
| 1037 |
}; |
| 1038 |
if json { |
| 1039 |
println!("{}", c.get_text(&path)?); |
| 1040 |
return Ok(0); |
| 1041 |
} |
| 1042 |
let list: Vec<hub_api::Drop> = c.get(&path)?; |
| 1043 |
if list.is_empty() { |
| 1044 |
println!("{}", ui::dim("No drops.")); |
| 1045 |
} |
| 1046 |
for d in &list { |
| 1047 |
println!("{}", drop_line(d)); |
| 1048 |
} |
| 1049 |
} |
| 1050 |
DropCmd::View { id, file } => { |
| 1051 |
let path = format!("/drops/{}", drop_id(&id)?); |
| 1052 |
if json && file.is_none() { |
| 1053 |
println!("{}", c.get_text(&path)?); |
| 1054 |
return Ok(0); |
| 1055 |
} |
| 1056 |
let d: hub_api::Drop = c.get(&path)?; |
| 1057 |
if let Some(name) = file { |
| 1058 |
let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?; |
| 1059 |
let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?; |
| 1060 |
print!("{content}"); |
| 1061 |
return Ok(0); |
| 1062 |
} |
| 1063 |
println!("{}", drop_line(&d)); |
| 1064 |
if !d.description.is_empty() { |
| 1065 |
println!("{}", d.description); |
| 1066 |
} |
| 1067 |
println!("{}", ui::kv("url", &d.url)); |
| 1068 |
println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url))); |
| 1069 |
for f in &d.files { |
| 1070 |
println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size))); |
| 1071 |
match &f.content { |
| 1072 |
Some(text) => { |
| 1073 |
print!("{text}"); |
| 1074 |
if !text.ends_with('\n') && !text.is_empty() { |
| 1075 |
println!(); |
| 1076 |
} |
| 1077 |
} |
| 1078 |
None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))), |
| 1079 |
} |
| 1080 |
} |
| 1081 |
} |
| 1082 |
DropCmd::Delete { id } => { |
| 1083 |
let id = drop_id(&id)?; |
| 1084 |
c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?; |
| 1085 |
println!("{} drop {id}", ui::ok("✔ deleted")); |
| 1086 |
} |
| 1087 |
} |
| 1088 |
Ok(0) |
| 1089 |
} |
| 1090 |
|
| 1091 |
|
| 1092 |
fn duration_ms(s: &str) -> Result<i64> { |
| 1093 |
let s = s.trim(); |
| 1094 |
let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())); |
| 1095 |
let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?; |
| 1096 |
let per = match unit { |
| 1097 |
"d" => 86_400_000, |
| 1098 |
"h" => 3_600_000, |
| 1099 |
"m" => 60_000, |
| 1100 |
_ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"), |
| 1101 |
}; |
| 1102 |
if n <= 0 { |
| 1103 |
bail!("a grant must last some time"); |
| 1104 |
} |
| 1105 |
Ok(n * per) |
| 1106 |
} |
| 1107 |
|
| 1108 |
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> { |
| 1109 |
use oxy_core::cert::{Grant, SignedGrant}; |
| 1110 |
use oxy_core::identity::{Identity, Scope}; |
| 1111 |
match cmd { |
| 1112 |
AgentCmd::Grant { name, scope, lasts } => { |
| 1113 |
let home = oxy_core::repo::default_home(); |
| 1114 |
let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| { |
| 1115 |
format!( |
| 1116 |
"{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell", |
| 1117 |
home.display() |
| 1118 |
) |
| 1119 |
})?; |
| 1120 |
let me: serde_json::Value = c.get("/user")?; |
| 1121 |
let username = me["username"].as_str().context("the hub did not say who you are")?; |
| 1122 |
let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?; |
| 1123 |
let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 1124 |
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; |
| 1125 |
let grant = Grant { |
| 1126 |
grantor: me_id.hash(), |
| 1127 |
subject: format!("agent:{name}@{username}"), |
| 1128 |
issuer: hub.hash(), |
| 1129 |
scope, |
| 1130 |
not_before: (now - 60_000) as u64, |
| 1131 |
expires: (now + duration_ms(&lasts)?) as u64, |
| 1132 |
}; |
| 1133 |
let signed = SignedGrant::sign(grant, &me_id, &sk); |
| 1134 |
let r: serde_json::Value = |
| 1135 |
c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?; |
| 1136 |
if json { |
| 1137 |
println!("{r}"); |
| 1138 |
return Ok(0); |
| 1139 |
} |
| 1140 |
println!( |
| 1141 |
"{} {} to act for you as {} ({}), until {}", |
| 1142 |
ui::ok("✔ granted"), |
| 1143 |
ui::strong(&name), |
| 1144 |
r["subject"].as_str().unwrap_or(""), |
| 1145 |
r["scope"].as_str().unwrap_or(""), |
| 1146 |
ui::date(r["expires_ms"].as_i64().unwrap_or(0)) |
| 1147 |
); |
| 1148 |
println!(" token (shown once): {}", r["token"].as_str().unwrap_or("")); |
| 1149 |
println!( |
| 1150 |
" {}", |
| 1151 |
ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless") |
| 1152 |
); |
| 1153 |
println!(" {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"]))); |
| 1154 |
Ok(0) |
| 1155 |
} |
| 1156 |
AgentCmd::List => { |
| 1157 |
let grants: Vec<serde_json::Value> = c.get("/agents/grants")?; |
| 1158 |
if json { |
| 1159 |
println!("{}", serde_json::to_string(&grants)?); |
| 1160 |
return Ok(0); |
| 1161 |
} |
| 1162 |
if grants.is_empty() { |
| 1163 |
println!("{}", ui::dim("no agent grants")); |
| 1164 |
} |
| 1165 |
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; |
| 1166 |
for g in grants { |
| 1167 |
let state = if g["revoked_ms"].is_i64() { |
| 1168 |
ui::bad("revoked") |
| 1169 |
} else if g["expires_ms"].as_i64().unwrap_or(0) <= now { |
| 1170 |
ui::dim("ended") |
| 1171 |
} else { |
| 1172 |
ui::ok("live") |
| 1173 |
}; |
| 1174 |
let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into()); |
| 1175 |
println!( |
| 1176 |
"#{:<4} {:<8} {} · {} · until {} · {}", |
| 1177 |
g["id"], |
| 1178 |
state, |
| 1179 |
ui::strong(g["subject"].as_str().unwrap_or("")), |
| 1180 |
g["scope"].as_str().unwrap_or(""), |
| 1181 |
ui::date(g["expires_ms"].as_i64().unwrap_or(0)), |
| 1182 |
ui::dim(&used) |
| 1183 |
); |
| 1184 |
} |
| 1185 |
Ok(0) |
| 1186 |
} |
| 1187 |
AgentCmd::Revoke { id } => { |
| 1188 |
c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?; |
| 1189 |
println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked")); |
| 1190 |
Ok(0) |
| 1191 |
} |
| 1192 |
} |
| 1193 |
} |
| 1194 |
|
| 1195 |
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> { |
| 1196 |
let hub = url.trim_end_matches('/').to_string(); |
| 1197 |
let token = match token.as_deref() { |
| 1198 |
Some("-") => { |
| 1199 |
eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:"); |
| 1200 |
let mut line = String::new(); |
| 1201 |
std::io::stdin().read_line(&mut line)?; |
| 1202 |
line.trim().to_string() |
| 1203 |
} |
| 1204 |
Some(t) => t.to_string(), |
| 1205 |
None => device_sign_in(&hub, ca.clone())?, |
| 1206 |
}; |
| 1207 |
if token.is_empty() { |
| 1208 |
bail!("no token given"); |
| 1209 |
} |
| 1210 |
let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() }; |
| 1211 |
let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?; |
| 1212 |
let account = me["username"].as_str().unwrap_or("?"); |
| 1213 |
|
| 1214 |
let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?; |
| 1215 |
let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c)); |
| 1216 |
oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 1217 |
cfg.default_hub = Some(hub.clone()); |
| 1218 |
cfg.save()?; |
| 1219 |
println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account)); |
| 1220 |
println!("{}", ui::dim(" oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it")); |
| 1221 |
Ok(0) |
| 1222 |
} |
| 1223 |
|
| 1224 |
|
| 1225 |
|
| 1226 |
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> { |
| 1227 |
let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() }; |
| 1228 |
let c = Client::new(&t)?; |
| 1229 |
let host = std::fs::read_to_string("/etc/hostname") |
| 1230 |
.ok() |
| 1231 |
.or_else(|| std::env::var("COMPUTERNAME").ok()) |
| 1232 |
.map(|h| h.trim().to_string()) |
| 1233 |
.filter(|h| !h.is_empty()); |
| 1234 |
let client = match host { |
| 1235 |
Some(h) => format!("oh on {h}"), |
| 1236 |
None => "oh".to_string(), |
| 1237 |
}; |
| 1238 |
let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"]; |
| 1239 |
let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?; |
| 1240 |
let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?; |
| 1241 |
if code != 200 { |
| 1242 |
bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body)); |
| 1243 |
} |
| 1244 |
let device = v["device_code"].as_str().context("no device code")?.to_string(); |
| 1245 |
let user = v["user_code"].as_str().unwrap_or("?"); |
| 1246 |
let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub); |
| 1247 |
let mut interval = v["interval"].as_u64().unwrap_or(5).max(1); |
| 1248 |
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900)); |
| 1249 |
eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user)); |
| 1250 |
eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…")); |
| 1251 |
loop { |
| 1252 |
std::thread::sleep(std::time::Duration::from_secs(interval)); |
| 1253 |
if std::time::Instant::now() > deadline { |
| 1254 |
bail!("the code expired before it was approved; run oh auth login again"); |
| 1255 |
} |
| 1256 |
let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?; |
| 1257 |
let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); |
| 1258 |
if code == 200 { |
| 1259 |
return v["access_token"].as_str().map(String::from).context("no token in the hub's answer"); |
| 1260 |
} |
| 1261 |
match v["error"].as_str() { |
| 1262 |
Some("authorization_pending") => {} |
| 1263 |
Some("slow_down") => interval += 5, |
| 1264 |
Some("access_denied") => bail!("the sign-in was denied on the web"), |
| 1265 |
Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"), |
| 1266 |
_ => bail!("signing in: HTTP {code}: {body}"), |
| 1267 |
} |
| 1268 |
} |
| 1269 |
} |
| 1270 |
|
| 1271 |
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> { |
| 1272 |
match (body, file) { |
| 1273 |
(Some(b), _) => Ok(b), |
| 1274 |
(None, Some(f)) if f == "-" => { |
| 1275 |
let mut s = String::new(); |
| 1276 |
std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; |
| 1277 |
Ok(s) |
| 1278 |
} |
| 1279 |
(None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")), |
| 1280 |
(None, None) => Ok(String::new()), |
| 1281 |
} |
| 1282 |
} |
| 1283 |
|
| 1284 |
fn issue_line(i: &Issue) -> String { |
| 1285 |
let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") }; |
| 1286 |
let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect(); |
| 1287 |
format!( |
| 1288 |
"{glyph} {} {}{}{}", |
| 1289 |
ui::dim(&format!("#{}", i.number)), |
| 1290 |
i.title, |
| 1291 |
if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) }, |
| 1292 |
ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms))) |
| 1293 |
) |
| 1294 |
} |
| 1295 |
|
| 1296 |
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> { |
| 1297 |
let base = t.repo_path()?; |
| 1298 |
match cmd { |
| 1299 |
IssueCmd::List { state } => { |
| 1300 |
let path = format!("{base}/issues?state={}", enc(&state)); |
| 1301 |
if json { |
| 1302 |
println!("{}", c.get_text(&path)?); |
| 1303 |
return Ok(0); |
| 1304 |
} |
| 1305 |
let list: Vec<Issue> = c.get(&path)?; |
| 1306 |
if list.is_empty() { |
| 1307 |
println!("{}", ui::dim(&format!("No {state} issues."))); |
| 1308 |
} |
| 1309 |
for i in &list { |
| 1310 |
println!("{}", issue_line(i)); |
| 1311 |
} |
| 1312 |
} |
| 1313 |
IssueCmd::View { number } => { |
| 1314 |
let path = format!("{base}/issues/{number}"); |
| 1315 |
if json { |
| 1316 |
println!("{}", c.get_text(&path)?); |
| 1317 |
return Ok(0); |
| 1318 |
} |
| 1319 |
let i: Issue = c.get(&path)?; |
| 1320 |
println!("{}", issue_line(&i)); |
| 1321 |
if !i.body.trim().is_empty() { |
| 1322 |
println!("\n{}\n", i.body.trim_end()); |
| 1323 |
} |
| 1324 |
let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?; |
| 1325 |
for cm in comments { |
| 1326 |
println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end()); |
| 1327 |
} |
| 1328 |
println!("{}", ui::dim(&i.url)); |
| 1329 |
} |
| 1330 |
IssueCmd::Create { title, body, body_file, label, project, column } => { |
| 1331 |
let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None }; |
| 1332 |
let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?; |
| 1333 |
if json { |
| 1334 |
println!("{}", serde_json::to_string(&i)?); |
| 1335 |
} else { |
| 1336 |
println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); |
| 1337 |
} |
| 1338 |
if let Some(n) = project { |
| 1339 |
let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() }; |
| 1340 |
let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?; |
| 1341 |
if !json { |
| 1342 |
println!("{} on project {n} as card {}", ui::ok("✔"), added.id); |
| 1343 |
} |
| 1344 |
} |
| 1345 |
} |
| 1346 |
IssueCmd::Close { number, reason } => { |
| 1347 |
let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?; |
| 1348 |
println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title); |
| 1349 |
} |
| 1350 |
IssueCmd::Reopen { number } => { |
| 1351 |
let i: Issue = |
| 1352 |
c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?; |
| 1353 |
println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title); |
| 1354 |
} |
| 1355 |
IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => { |
| 1356 |
let body = match (&body, &body_file) { |
| 1357 |
(None, None) => None, |
| 1358 |
_ => Some(body_of(body, body_file)?), |
| 1359 |
}; |
| 1360 |
let labels = if no_labels { |
| 1361 |
Some(Vec::new()) |
| 1362 |
} else if label.is_empty() { |
| 1363 |
None |
| 1364 |
} else { |
| 1365 |
Some(label) |
| 1366 |
}; |
| 1367 |
let assignees = if no_assignees { |
| 1368 |
Some(Vec::new()) |
| 1369 |
} else if assignee.is_empty() { |
| 1370 |
None |
| 1371 |
} else { |
| 1372 |
Some(assignee) |
| 1373 |
}; |
| 1374 |
if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() { |
| 1375 |
bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone"); |
| 1376 |
} |
| 1377 |
let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone }; |
| 1378 |
let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?; |
| 1379 |
if json { |
| 1380 |
println!("{}", serde_json::to_string(&i)?); |
| 1381 |
} else { |
| 1382 |
println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); |
| 1383 |
} |
| 1384 |
} |
| 1385 |
IssueCmd::Label(change) => { |
| 1386 |
let path = format!("{base}/issues/{}", change.number); |
| 1387 |
let now: Issue = c.get(&path)?; |
| 1388 |
let labels = change.apply(&now.labels)?; |
| 1389 |
let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None }; |
| 1390 |
let i: Issue = c.send("PATCH", &path, &edit)?; |
| 1391 |
if json { |
| 1392 |
println!("{}", serde_json::to_string(&i)?); |
| 1393 |
} else { |
| 1394 |
println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels)); |
| 1395 |
} |
| 1396 |
} |
| 1397 |
IssueCmd::Comment { number, body } => { |
| 1398 |
c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1399 |
println!("{} commented on #{number}", ui::ok("✔")); |
| 1400 |
} |
| 1401 |
} |
| 1402 |
Ok(0) |
| 1403 |
} |
| 1404 |
|
| 1405 |
fn source_name(s: &hub_api::ProposalSource) -> String { |
| 1406 |
match s { |
| 1407 |
hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(), |
| 1408 |
hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"), |
| 1409 |
hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()), |
| 1410 |
} |
| 1411 |
} |
| 1412 |
|
| 1413 |
fn proposal_line(p: &Proposal) -> String { |
| 1414 |
let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default(); |
| 1415 |
let glyph = match state.as_str() { |
| 1416 |
"open" => ui::ok("●"), |
| 1417 |
"draft" => ui::dim("◌"), |
| 1418 |
"landed" => ui::strong("✔"), |
| 1419 |
_ => ui::dim("○"), |
| 1420 |
}; |
| 1421 |
format!( |
| 1422 |
"{glyph} {} {} {}{}", |
| 1423 |
ui::dim(&format!("#{}", p.number)), |
| 1424 |
p.title, |
| 1425 |
ui::dim(&format!("{} → {}", source_name(&p.source), p.target)), |
| 1426 |
ui::dim(&format!(" · {} · {state}", p.author)) |
| 1427 |
) |
| 1428 |
} |
| 1429 |
|
| 1430 |
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> { |
| 1431 |
let base = t.repo_path()?; |
| 1432 |
match cmd { |
| 1433 |
ProposalCmd::List { state } => { |
| 1434 |
let path = format!("{base}/proposals?state={state}"); |
| 1435 |
if json { |
| 1436 |
println!("{}", c.get_text(&path)?); |
| 1437 |
return Ok(0); |
| 1438 |
} |
| 1439 |
let list: Vec<Proposal> = c.get(&path)?; |
| 1440 |
if list.is_empty() { |
| 1441 |
println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace(" ", " "))); |
| 1442 |
} |
| 1443 |
for p in &list { |
| 1444 |
println!("{}", proposal_line(p)); |
| 1445 |
} |
| 1446 |
} |
| 1447 |
ProposalCmd::View { number } => { |
| 1448 |
let path = format!("{base}/proposals/{number}"); |
| 1449 |
if json { |
| 1450 |
println!("{}", c.get_text(&path)?); |
| 1451 |
return Ok(0); |
| 1452 |
} |
| 1453 |
let p: Proposal = c.get(&path)?; |
| 1454 |
println!("{}", proposal_line(&p)); |
| 1455 |
if !p.body.trim().is_empty() { |
| 1456 |
println!("\n{}\n", p.body.trim_end()); |
| 1457 |
} |
| 1458 |
println!("{}", ui::kv("changes", &p.changes.len().to_string())); |
| 1459 |
for ch in &p.changes { |
| 1460 |
println!(" {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or("")); |
| 1461 |
} |
| 1462 |
println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", "))); |
| 1463 |
if p.landable { |
| 1464 |
println!("{} can land", ui::ok("✔")); |
| 1465 |
} else { |
| 1466 |
for b in &p.blockers { |
| 1467 |
println!("{} {b}", ui::bad("✘")); |
| 1468 |
} |
| 1469 |
} |
| 1470 |
if p.conflicted { |
| 1471 |
println!("{} landing it would leave conflicts", ui::bad("!")); |
| 1472 |
} |
| 1473 |
println!("{}", ui::dim(&p.url)); |
| 1474 |
} |
| 1475 |
ProposalCmd::Create { title, body, body_file, from, into, draft } => { |
| 1476 |
let target = match into { |
| 1477 |
Some(i) => i, |
| 1478 |
None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(), |
| 1479 |
}; |
| 1480 |
let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft }; |
| 1481 |
let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?; |
| 1482 |
if json { |
| 1483 |
println!("{}", serde_json::to_string(&p)?); |
| 1484 |
} else { |
| 1485 |
println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); |
| 1486 |
} |
| 1487 |
} |
| 1488 |
ProposalCmd::Edit { number, title, body, body_file } => { |
| 1489 |
let body = match (&body, &body_file) { |
| 1490 |
(None, None) => None, |
| 1491 |
_ => Some(body_of(body, body_file)?), |
| 1492 |
}; |
| 1493 |
if title.is_none() && body.is_none() { |
| 1494 |
bail!("say what to change: --title, --body or --body-file"); |
| 1495 |
} |
| 1496 |
let edit = hub_api::ProposalEdit { title, body, ..Default::default() }; |
| 1497 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; |
| 1498 |
if json { |
| 1499 |
println!("{}", serde_json::to_string(&p)?); |
| 1500 |
} else { |
| 1501 |
println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); |
| 1502 |
} |
| 1503 |
} |
| 1504 |
ProposalCmd::Label(change) => { |
| 1505 |
let path = format!("{base}/proposals/{}", change.number); |
| 1506 |
let now: Proposal = c.get(&path)?; |
| 1507 |
let labels = change.apply(&now.labels)?; |
| 1508 |
let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() }; |
| 1509 |
let p: Proposal = c.send("PATCH", &path, &edit)?; |
| 1510 |
if json { |
| 1511 |
println!("{}", serde_json::to_string(&p)?); |
| 1512 |
} else { |
| 1513 |
println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels)); |
| 1514 |
} |
| 1515 |
} |
| 1516 |
ProposalCmd::Comment { number, body, body_file } => { |
| 1517 |
let body = body_of(body, body_file)?; |
| 1518 |
if body.trim().is_empty() { |
| 1519 |
bail!("give the comment with --body or --body-file"); |
| 1520 |
} |
| 1521 |
c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1522 |
println!("{} commented on #{number}", ui::ok("✔")); |
| 1523 |
} |
| 1524 |
ProposalCmd::Land { number, when_ready: true, off, .. } => { |
| 1525 |
let path = format!("{base}/proposals/{number}/auto-land"); |
| 1526 |
let p: Proposal = |
| 1527 |
if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? }; |
| 1528 |
if json { |
| 1529 |
println!("{}", serde_json::to_string(&p)?); |
| 1530 |
} else if p.landed.is_some() { |
| 1531 |
println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target); |
| 1532 |
} else if p.auto_land.is_some() { |
| 1533 |
println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number); |
| 1534 |
} else { |
| 1535 |
println!("{} #{} will not land by itself", ui::ok("✔"), p.number); |
| 1536 |
} |
| 1537 |
} |
| 1538 |
ProposalCmd::Land { number, over_checks, .. } => { |
| 1539 |
let body = match &over_checks { |
| 1540 |
Some(r) => serde_json::json!({ "over_checks": r }), |
| 1541 |
None => serde_json::json!({}), |
| 1542 |
}; |
| 1543 |
let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?; |
| 1544 |
if json { |
| 1545 |
println!("{}", serde_json::to_string(&p)?); |
| 1546 |
} else { |
| 1547 |
println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target); |
| 1548 |
} |
| 1549 |
} |
| 1550 |
ProposalCmd::Close { number, message } => { |
| 1551 |
if let Some(body) = message { |
| 1552 |
c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1553 |
} |
| 1554 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?; |
| 1555 |
if json { |
| 1556 |
println!("{}", serde_json::to_string(&p)?); |
| 1557 |
} else { |
| 1558 |
println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title); |
| 1559 |
} |
| 1560 |
} |
| 1561 |
ProposalCmd::Reopen { number } => { |
| 1562 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?; |
| 1563 |
if json { |
| 1564 |
println!("{}", serde_json::to_string(&p)?); |
| 1565 |
} else { |
| 1566 |
println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title); |
| 1567 |
} |
| 1568 |
} |
| 1569 |
ProposalCmd::Ready { number, undo } => { |
| 1570 |
let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() }; |
| 1571 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; |
| 1572 |
if json { |
| 1573 |
println!("{}", serde_json::to_string(&p)?); |
| 1574 |
} else if undo { |
| 1575 |
println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title); |
| 1576 |
} else { |
| 1577 |
println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title); |
| 1578 |
} |
| 1579 |
} |
| 1580 |
ProposalCmd::Checks { number } => { |
| 1581 |
let path = format!("{base}/proposals/{number}/checks"); |
| 1582 |
if json { |
| 1583 |
println!("{}", c.get_text(&path)?); |
| 1584 |
return Ok(0); |
| 1585 |
} |
| 1586 |
let checks: Vec<hub_api::Check> = c.get(&path)?; |
| 1587 |
if checks.is_empty() { |
| 1588 |
println!("{}", ui::dim("No checks yet.")); |
| 1589 |
} |
| 1590 |
for ch in checks { |
| 1591 |
println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary)); |
| 1592 |
} |
| 1593 |
} |
| 1594 |
} |
| 1595 |
Ok(0) |
| 1596 |
} |
| 1597 |
|
| 1598 |
fn run_line(r: &FlowRun) -> String { |
| 1599 |
let what = |
| 1600 |
if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() }; |
| 1601 |
format!( |
| 1602 |
"{} {} {} {}", |
| 1603 |
ui::status(&r.status), |
| 1604 |
ui::dim(&format!("#{}", r.number)), |
| 1605 |
what, |
| 1606 |
ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms))) |
| 1607 |
) |
| 1608 |
} |
| 1609 |
|
| 1610 |
fn print_run(r: &FlowRun) { |
| 1611 |
println!("{}", run_line(r)); |
| 1612 |
for j in &r.jobs { |
| 1613 |
let dur = match (j.started_ms, j.finished_ms) { |
| 1614 |
(Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0), |
| 1615 |
_ => String::new(), |
| 1616 |
}; |
| 1617 |
let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) }; |
| 1618 |
println!(" {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}"))); |
| 1619 |
|
| 1620 |
|
| 1621 |
if j.status == "queued" && !j.waiting.is_empty() { |
| 1622 |
println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); |
| 1623 |
} else if !j.placed.is_empty() { |
| 1624 |
println!(" {}", ui::dim(&format!("placed: {}", j.placed))); |
| 1625 |
} |
| 1626 |
} |
| 1627 |
if !r.error.is_empty() { |
| 1628 |
println!("{}", ui::bad(&r.error)); |
| 1629 |
} |
| 1630 |
println!("{}", ui::dim(&r.url)); |
| 1631 |
} |
| 1632 |
|
| 1633 |
fn live(status: &str) -> bool { |
| 1634 |
matches!(status, "queued" | "running") |
| 1635 |
} |
| 1636 |
|
| 1637 |
|
| 1638 |
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> { |
| 1639 |
let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?; |
| 1640 |
if json { |
| 1641 |
println!("{done}"); |
| 1642 |
} else { |
| 1643 |
println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or("")); |
| 1644 |
} |
| 1645 |
Ok(()) |
| 1646 |
} |
| 1647 |
|
| 1648 |
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> { |
| 1649 |
let path = format!("{base}/flow/runs/{number}"); |
| 1650 |
let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new(); |
| 1651 |
loop { |
| 1652 |
let r: FlowRun = c.get(&path)?; |
| 1653 |
if !json { |
| 1654 |
for j in &r.jobs { |
| 1655 |
let shown = format!("{}\u{0}{}", j.status, j.waiting); |
| 1656 |
if seen.get(&j.name) != Some(&shown) { |
| 1657 |
println!("{} {}", ui::status(&j.status), j.name); |
| 1658 |
if j.status == "queued" && !j.waiting.is_empty() { |
| 1659 |
println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); |
| 1660 |
} |
| 1661 |
seen.insert(j.name.clone(), shown); |
| 1662 |
} |
| 1663 |
} |
| 1664 |
} |
| 1665 |
if !live(&r.status) { |
| 1666 |
if json { |
| 1667 |
println!("{}", serde_json::to_string(&r)?); |
| 1668 |
} else { |
| 1669 |
println!("{} run #{} {}", ui::status(&r.status), r.number, r.status); |
| 1670 |
} |
| 1671 |
return Ok(if r.status == "passed" { 0 } else { 1 }); |
| 1672 |
} |
| 1673 |
std::thread::sleep(Duration::from_secs(3)); |
| 1674 |
} |
| 1675 |
} |
| 1676 |
|
| 1677 |
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> { |
| 1678 |
let base = t.repo_path()?; |
| 1679 |
match cmd { |
| 1680 |
RunCmd::List { limit } => { |
| 1681 |
let path = format!("{base}/flow/runs?limit={limit}"); |
| 1682 |
if json { |
| 1683 |
println!("{}", c.get_text(&path)?); |
| 1684 |
return Ok(0); |
| 1685 |
} |
| 1686 |
let runs: Vec<FlowRun> = c.get(&path)?; |
| 1687 |
if runs.is_empty() { |
| 1688 |
println!("{}", ui::dim("No runs yet.")); |
| 1689 |
} |
| 1690 |
for r in &runs { |
| 1691 |
println!("{}", run_line(r)); |
| 1692 |
} |
| 1693 |
} |
| 1694 |
RunCmd::View { number } => { |
| 1695 |
let path = format!("{base}/flow/runs/{number}"); |
| 1696 |
if json { |
| 1697 |
println!("{}", c.get_text(&path)?); |
| 1698 |
return Ok(0); |
| 1699 |
} |
| 1700 |
print_run(&c.get(&path)?); |
| 1701 |
} |
| 1702 |
RunCmd::Start { bookmark, change, jobs, watch: follow } => { |
| 1703 |
let mut body = match (bookmark, change) { |
| 1704 |
(_, Some(ch)) => serde_json::json!({ "change": ch }), |
| 1705 |
(Some(b), None) => serde_json::json!({ "bookmark": b }), |
| 1706 |
(None, None) => serde_json::json!({}), |
| 1707 |
}; |
| 1708 |
if !jobs.is_empty() { |
| 1709 |
body["jobs"] = serde_json::json!(jobs); |
| 1710 |
} |
| 1711 |
let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?; |
| 1712 |
let n = started["number"].as_i64().context("the hub named no run")?; |
| 1713 |
if !json || !follow { |
| 1714 |
if json { |
| 1715 |
println!("{started}"); |
| 1716 |
} else { |
| 1717 |
println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or(""))); |
| 1718 |
} |
| 1719 |
} |
| 1720 |
if follow { |
| 1721 |
return watch(c, &base, n, json); |
| 1722 |
} |
| 1723 |
} |
| 1724 |
RunCmd::Watch { number } => return watch(c, &base, number, json), |
| 1725 |
RunCmd::Log { number, job } => { |
| 1726 |
let mut after = 0; |
| 1727 |
loop { |
| 1728 |
let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job)); |
| 1729 |
let lines: Vec<FlowLogLine> = c.get(&path)?; |
| 1730 |
if lines.is_empty() { |
| 1731 |
break; |
| 1732 |
} |
| 1733 |
for l in &lines { |
| 1734 |
if json { |
| 1735 |
println!("{}", serde_json::to_string(l)?); |
| 1736 |
} else if l.stream == "flow" { |
| 1737 |
println!("{}", ui::dim(&l.text)); |
| 1738 |
} else { |
| 1739 |
println!("{}", l.text); |
| 1740 |
} |
| 1741 |
} |
| 1742 |
after = lines.last().map(|l| l.seq).unwrap_or(after); |
| 1743 |
} |
| 1744 |
} |
| 1745 |
RunCmd::Rerun { number, job: Some(job) } => { |
| 1746 |
let queued: serde_json::Value = |
| 1747 |
c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?; |
| 1748 |
if json { |
| 1749 |
println!("{queued}"); |
| 1750 |
} else { |
| 1751 |
let n = queued["queued"].as_i64().unwrap_or(1); |
| 1752 |
let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() }; |
| 1753 |
println!("{} queued {job} of run #{number} again{with}", ui::ok("✔")); |
| 1754 |
} |
| 1755 |
} |
| 1756 |
RunCmd::Rerun { number, job: None } => { |
| 1757 |
let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?; |
| 1758 |
if json { |
| 1759 |
println!("{started}"); |
| 1760 |
} else { |
| 1761 |
println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or(""))); |
| 1762 |
} |
| 1763 |
} |
| 1764 |
RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?, |
| 1765 |
RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?, |
| 1766 |
RunCmd::Cancel { number } => { |
| 1767 |
let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?; |
| 1768 |
if json { |
| 1769 |
println!("{done}"); |
| 1770 |
} else { |
| 1771 |
println!("{} cancelled run #{number}", ui::ok("✔")); |
| 1772 |
} |
| 1773 |
} |
| 1774 |
} |
| 1775 |
Ok(0) |
| 1776 |
} |
| 1777 |
|
| 1778 |
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> { |
| 1779 |
let base = t.repo_path()?; |
| 1780 |
match cmd { |
| 1781 |
LabelCmd::List => { |
| 1782 |
let path = format!("{base}/labels"); |
| 1783 |
if json { |
| 1784 |
println!("{}", c.get_text(&path)?); |
| 1785 |
return Ok(0); |
| 1786 |
} |
| 1787 |
let labels: Vec<hub_api::Label> = c.get(&path)?; |
| 1788 |
if labels.is_empty() { |
| 1789 |
println!("{}", ui::dim("No labels.")); |
| 1790 |
} |
| 1791 |
for l in labels { |
| 1792 |
println!("{} {} {}", ui::dim(&l.colour), l.name, ui::dim(&l.description)); |
| 1793 |
} |
| 1794 |
} |
| 1795 |
LabelCmd::Create { name, colour, description } => { |
| 1796 |
let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?; |
| 1797 |
if json { |
| 1798 |
println!("{}", serde_json::to_string(&l)?); |
| 1799 |
} else { |
| 1800 |
println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour)); |
| 1801 |
} |
| 1802 |
} |
| 1803 |
LabelCmd::Delete { name } => { |
| 1804 |
c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?; |
| 1805 |
println!("{} deleted label {name}", ui::ok("✔")); |
| 1806 |
} |
| 1807 |
} |
| 1808 |
Ok(0) |
| 1809 |
} |
| 1810 |
|
| 1811 |
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> { |
| 1812 |
let base = match (&org, site) { |
| 1813 |
(Some(o), _) => format!("/orgs/{}/assistants", enc(o)), |
| 1814 |
(None, true) => "/admin/assistants".to_string(), |
| 1815 |
(None, false) => format!("{}/assistants", t.repo_path()?), |
| 1816 |
}; |
| 1817 |
match cmd { |
| 1818 |
AssistantCmd::List => { |
| 1819 |
if json { |
| 1820 |
println!("{}", c.get_text(&base)?); |
| 1821 |
return Ok(0); |
| 1822 |
} |
| 1823 |
let list: Vec<hub_api::Assistant> = c.get(&base)?; |
| 1824 |
if list.is_empty() { |
| 1825 |
println!("{}", ui::dim("No assistants.")); |
| 1826 |
} |
| 1827 |
for a in list { |
| 1828 |
let state = if a.enabled && !a.off_above { |
| 1829 |
ui::ok("on") |
| 1830 |
} else if a.off_above { |
| 1831 |
ui::dim("off above") |
| 1832 |
} else { |
| 1833 |
ui::dim("off") |
| 1834 |
}; |
| 1835 |
let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) }; |
| 1836 |
println!("{} {} {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from); |
| 1837 |
} |
| 1838 |
} |
| 1839 |
AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => { |
| 1840 |
let token = match token_env { |
| 1841 |
Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?, |
| 1842 |
None => String::new(), |
| 1843 |
}; |
| 1844 |
let body = |
| 1845 |
hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None }; |
| 1846 |
let r: serde_json::Value = c.send("POST", &base, &body)?; |
| 1847 |
println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved")); |
| 1848 |
} |
| 1849 |
AssistantCmd::Remove { name } => { |
| 1850 |
c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?; |
| 1851 |
println!("{} removed {name}", ui::ok("✔")); |
| 1852 |
} |
| 1853 |
AssistantCmd::Prompt { set } => { |
| 1854 |
let p: hub_api::AssistantPrompt = match set { |
| 1855 |
Some(path) => { |
| 1856 |
let text = if path.as_os_str() == "-" { |
| 1857 |
let mut s = String::new(); |
| 1858 |
std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; |
| 1859 |
s |
| 1860 |
} else { |
| 1861 |
std::fs::read_to_string(&path)? |
| 1862 |
}; |
| 1863 |
c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })? |
| 1864 |
} |
| 1865 |
None => c.get(&format!("{base}/prompt"))?, |
| 1866 |
}; |
| 1867 |
if json { |
| 1868 |
println!("{}", serde_json::to_string(&p)?); |
| 1869 |
return Ok(0); |
| 1870 |
} |
| 1871 |
for (from, text) in &p.inherited { |
| 1872 |
println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text); |
| 1873 |
} |
| 1874 |
if p.prompt.is_empty() { |
| 1875 |
println!("{}", ui::dim("No prompt of its own.")); |
| 1876 |
} else { |
| 1877 |
println!("{}\n{}", ui::dim("── this level"), p.prompt); |
| 1878 |
} |
| 1879 |
} |
| 1880 |
} |
| 1881 |
Ok(0) |
| 1882 |
} |
| 1883 |
|
| 1884 |
fn project_line(p: &hub_api::Project) -> String { |
| 1885 |
let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") }; |
| 1886 |
let private = if p.public { "" } else { " · private" }; |
| 1887 |
format!("{glyph} {} {} {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms)))) |
| 1888 |
} |
| 1889 |
|
| 1890 |
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> { |
| 1891 |
let owner = match owner { |
| 1892 |
Some(o) => o, |
| 1893 |
None => t.repo()?.0.to_string(), |
| 1894 |
}; |
| 1895 |
let base = format!("/projects/{}", enc(&owner)); |
| 1896 |
let state = |number: i64, closed: bool, verb: &str| -> Result<()> { |
| 1897 |
let p: hub_api::Project = |
| 1898 |
c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?; |
| 1899 |
if json { |
| 1900 |
println!("{}", serde_json::to_string(&p)?); |
| 1901 |
} else { |
| 1902 |
println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title); |
| 1903 |
} |
| 1904 |
Ok(()) |
| 1905 |
}; |
| 1906 |
match cmd { |
| 1907 |
ProjectCmd::List => { |
| 1908 |
if json { |
| 1909 |
println!("{}", c.get_text(&base)?); |
| 1910 |
return Ok(0); |
| 1911 |
} |
| 1912 |
let list: Vec<hub_api::Project> = c.get(&base)?; |
| 1913 |
if list.is_empty() { |
| 1914 |
println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE"))); |
| 1915 |
} |
| 1916 |
for p in &list { |
| 1917 |
println!("{}", project_line(p)); |
| 1918 |
} |
| 1919 |
} |
| 1920 |
ProjectCmd::View { number, archived } => { |
| 1921 |
let path = format!("{base}/{number}"); |
| 1922 |
let cards = format!("{path}/cards?archived=true"); |
| 1923 |
if json { |
| 1924 |
println!("{}", c.get_text(if archived { &cards } else { &path })?); |
| 1925 |
return Ok(0); |
| 1926 |
} |
| 1927 |
let mut b: hub_api::Board = c.get(&path)?; |
| 1928 |
if archived { |
| 1929 |
b.columns = c.get(&cards)?; |
| 1930 |
} |
| 1931 |
println!("{}", project_line(&b.project)); |
| 1932 |
if !b.project.description.is_empty() { |
| 1933 |
println!("{}", b.project.description); |
| 1934 |
} |
| 1935 |
for col in &b.columns { |
| 1936 |
println!(); |
| 1937 |
println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id))); |
| 1938 |
if col.cards.is_empty() { |
| 1939 |
println!(" {}", ui::dim("(empty)")); |
| 1940 |
} |
| 1941 |
for card in &col.cards { |
| 1942 |
let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() }; |
| 1943 |
let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) }; |
| 1944 |
let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect(); |
| 1945 |
tags.extend(card.assignees.iter().map(|a| format!("@{a}"))); |
| 1946 |
let tags = if tags.is_empty() { String::new() } else { format!(" {}", ui::dim(&tags.join(" "))) }; |
| 1947 |
println!(" {} {what}{st} {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title); |
| 1948 |
} |
| 1949 |
} |
| 1950 |
println!("{}", ui::dim(&format!("\n{}", b.project.url))); |
| 1951 |
} |
| 1952 |
ProjectCmd::Create { title, description, private } => { |
| 1953 |
let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?; |
| 1954 |
if json { |
| 1955 |
println!("{}", serde_json::to_string(&p)?); |
| 1956 |
} else { |
| 1957 |
println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url)); |
| 1958 |
} |
| 1959 |
} |
| 1960 |
ProjectCmd::Close { number } => state(number, true, "closed")?, |
| 1961 |
ProjectCmd::Reopen { number } => state(number, false, "reopened")?, |
| 1962 |
ProjectCmd::Transfer { number, to } => { |
| 1963 |
let p: hub_api::Project = |
| 1964 |
c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?; |
| 1965 |
if json { |
| 1966 |
println!("{}", serde_json::to_string(&p)?); |
| 1967 |
} else { |
| 1968 |
println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url); |
| 1969 |
} |
| 1970 |
} |
| 1971 |
ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => { |
| 1972 |
|
| 1973 |
|
| 1974 |
let reference = match reference { |
| 1975 |
None => String::new(), |
| 1976 |
Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') { |
| 1977 |
Some((o, rest)) if o == owner => rest.to_string(), |
| 1978 |
Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"), |
| 1979 |
None => r, |
| 1980 |
}, |
| 1981 |
Some(r) => { |
| 1982 |
let n = r.trim_start_matches('#'); |
| 1983 |
if n.parse::<i64>().is_err() { |
| 1984 |
bail!("{r}: give an issue or proposal number, or NAME#N"); |
| 1985 |
} |
| 1986 |
format!("{}#{n}", t.repo()?.1) |
| 1987 |
} |
| 1988 |
}; |
| 1989 |
let note = note.unwrap_or_default(); |
| 1990 |
if reference.is_empty() && note.is_empty() { |
| 1991 |
bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT"); |
| 1992 |
} |
| 1993 |
let card: hub_api::ProjectCard = |
| 1994 |
c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?; |
| 1995 |
if json { |
| 1996 |
println!("{}", serde_json::to_string(&card)?); |
| 1997 |
} else { |
| 1998 |
println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference }); |
| 1999 |
} |
| 2000 |
} |
| 2001 |
ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) { |
| 2002 |
(Some(card), None) => { |
| 2003 |
c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?; |
| 2004 |
println!("{} card {card} moved to {column}", ui::ok("✔")); |
| 2005 |
} |
| 2006 |
(None, Some(from)) => { |
| 2007 |
let r: hub_api::CardsMoved = c.send( |
| 2008 |
"POST", |
| 2009 |
&format!("{base}/{number}/cards/move"), |
| 2010 |
&hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run }, |
| 2011 |
)?; |
| 2012 |
if json { |
| 2013 |
println!("{}", serde_json::to_string(&r)?); |
| 2014 |
return Ok(0); |
| 2015 |
} |
| 2016 |
let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() }; |
| 2017 |
for m in &r.moved { |
| 2018 |
println!(" {} {} {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title)); |
| 2019 |
} |
| 2020 |
let verb = if dry_run { "would move" } else { "moved" }; |
| 2021 |
println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len()); |
| 2022 |
} |
| 2023 |
_ => bail!("name a card, or --from COLUMN to move every card of a column"), |
| 2024 |
}, |
| 2025 |
ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => { |
| 2026 |
let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) { |
| 2027 |
None => None, |
| 2028 |
Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?), |
| 2029 |
}; |
| 2030 |
let r: hub_api::CardsArchived = c.send( |
| 2031 |
"POST", |
| 2032 |
&format!("{base}/{number}/cards/archive"), |
| 2033 |
&hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run }, |
| 2034 |
)?; |
| 2035 |
if json { |
| 2036 |
println!("{}", serde_json::to_string(&r)?); |
| 2037 |
return Ok(0); |
| 2038 |
} |
| 2039 |
let verb = if dry_run { "would archive" } else { "archived" }; |
| 2040 |
for a in &r.archived { |
| 2041 |
let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() }; |
| 2042 |
println!(" {verb} {name} {}", ui::dim(&a.title)); |
| 2043 |
} |
| 2044 |
println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len()); |
| 2045 |
} |
| 2046 |
ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => { |
| 2047 |
c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?; |
| 2048 |
println!("{} card {card} restored", ui::ok("✔")); |
| 2049 |
} |
| 2050 |
ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => { |
| 2051 |
c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?; |
| 2052 |
println!("{} card {card} removed", ui::ok("✔")); |
| 2053 |
} |
| 2054 |
} |
| 2055 |
Ok(0) |
| 2056 |
} |
| 2057 |
|
| 2058 |
fn milestone_line(m: &hub_api::Milestone) -> String { |
| 2059 |
let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") }; |
| 2060 |
let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default(); |
| 2061 |
format!("{glyph} {} {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due)) |
| 2062 |
} |
| 2063 |
|
| 2064 |
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> { |
| 2065 |
let base = t.repo_path()?; |
| 2066 |
let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> { |
| 2067 |
let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?; |
| 2068 |
if json { |
| 2069 |
println!("{}", serde_json::to_string(&m)?); |
| 2070 |
} else { |
| 2071 |
println!("{} {verb} milestone {}", ui::ok("✔"), m.title); |
| 2072 |
} |
| 2073 |
Ok(()) |
| 2074 |
}; |
| 2075 |
match cmd { |
| 2076 |
MilestoneCmd::List => { |
| 2077 |
let path = format!("{base}/milestones"); |
| 2078 |
if json { |
| 2079 |
println!("{}", c.get_text(&path)?); |
| 2080 |
return Ok(0); |
| 2081 |
} |
| 2082 |
let list: Vec<hub_api::Milestone> = c.get(&path)?; |
| 2083 |
if list.is_empty() { |
| 2084 |
println!("{}", ui::dim("No milestones.")); |
| 2085 |
} |
| 2086 |
for m in &list { |
| 2087 |
println!("{}", milestone_line(m)); |
| 2088 |
} |
| 2089 |
} |
| 2090 |
MilestoneCmd::Create { title, description, due } => { |
| 2091 |
let m: hub_api::Milestone = |
| 2092 |
c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?; |
| 2093 |
if json { |
| 2094 |
println!("{}", serde_json::to_string(&m)?); |
| 2095 |
} else { |
| 2096 |
println!("{} milestone {}", ui::ok("✔"), m.title); |
| 2097 |
} |
| 2098 |
} |
| 2099 |
MilestoneCmd::Edit { title, rename, description, due } => { |
| 2100 |
if rename.is_none() && description.is_none() && due.is_none() { |
| 2101 |
bail!("say what to change: --rename, --description or --due"); |
| 2102 |
} |
| 2103 |
edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?; |
| 2104 |
} |
| 2105 |
MilestoneCmd::Close { title } => { |
| 2106 |
edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?; |
| 2107 |
} |
| 2108 |
MilestoneCmd::Reopen { title } => { |
| 2109 |
edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?; |
| 2110 |
} |
| 2111 |
} |
| 2112 |
Ok(0) |
| 2113 |
} |
| 2114 |
|
| 2115 |
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> { |
| 2116 |
let base = t.repo_path()?; |
| 2117 |
match cmd { |
| 2118 |
TagCmd::List => { |
| 2119 |
let path = format!("{base}/tags"); |
| 2120 |
if json { |
| 2121 |
println!("{}", c.get_text(&path)?); |
| 2122 |
return Ok(0); |
| 2123 |
} |
| 2124 |
let tags: Vec<Tag> = c.get(&path)?; |
| 2125 |
if tags.is_empty() { |
| 2126 |
println!("{}", ui::dim("no tags")); |
| 2127 |
} |
| 2128 |
for t in tags { |
| 2129 |
let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect(); |
| 2130 |
let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into()); |
| 2131 |
println!("{} {} {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer)); |
| 2132 |
} |
| 2133 |
} |
| 2134 |
TagCmd::Create { name, target, message } => { |
| 2135 |
let new = hub_api::NewTag { name, target, message }; |
| 2136 |
let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?; |
| 2137 |
if json { |
| 2138 |
println!("{}", serde_json::to_string(&made)?); |
| 2139 |
} else { |
| 2140 |
println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len()))); |
| 2141 |
} |
| 2142 |
} |
| 2143 |
TagCmd::Delete { name, reason } => { |
| 2144 |
let reason = reason.unwrap_or_default(); |
| 2145 |
c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?; |
| 2146 |
if json { |
| 2147 |
println!("{}", serde_json::json!({ "withdrawn": name })); |
| 2148 |
} else { |
| 2149 |
println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)")); |
| 2150 |
} |
| 2151 |
} |
| 2152 |
} |
| 2153 |
Ok(0) |
| 2154 |
} |
| 2155 |
|
| 2156 |
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> { |
| 2157 |
let base = t.repo_path()?; |
| 2158 |
match cmd { |
| 2159 |
ReleaseCmd::List => { |
| 2160 |
let path = format!("{base}/releases"); |
| 2161 |
if json { |
| 2162 |
println!("{}", c.get_text(&path)?); |
| 2163 |
return Ok(0); |
| 2164 |
} |
| 2165 |
let list: Vec<Release> = c.get(&path)?; |
| 2166 |
if list.is_empty() { |
| 2167 |
println!("{}", ui::dim("No releases.")); |
| 2168 |
} |
| 2169 |
for r in &list { |
| 2170 |
println!( |
| 2171 |
"{} {} {}{}", |
| 2172 |
if r.latest { ui::ok("●") } else { ui::dim("○") }, |
| 2173 |
ui::strong(&r.tag), |
| 2174 |
r.title, |
| 2175 |
ui::dim(&format!( |
| 2176 |
" · {} asset{} · {}", |
| 2177 |
r.assets.len(), |
| 2178 |
if r.assets.len() == 1 { "" } else { "s" }, |
| 2179 |
ui::ago(r.created_ms) |
| 2180 |
)) |
| 2181 |
); |
| 2182 |
} |
| 2183 |
} |
| 2184 |
ReleaseCmd::Create { tag, title, notes, prerelease } => { |
| 2185 |
let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease }; |
| 2186 |
let r: Release = c.send("POST", &format!("{base}/releases"), &new)?; |
| 2187 |
if json { |
| 2188 |
println!("{}", serde_json::to_string(&r)?); |
| 2189 |
} else { |
| 2190 |
println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); |
| 2191 |
} |
| 2192 |
} |
| 2193 |
ReleaseCmd::Edit { tag, title, notes, prerelease } => { |
| 2194 |
let notes = match notes.as_deref() { |
| 2195 |
Some("-") => Some(body_of(None, Some("-".into()))?), |
| 2196 |
_ => notes, |
| 2197 |
}; |
| 2198 |
if title.is_none() && notes.is_none() && prerelease.is_none() { |
| 2199 |
bail!("say what to change: --title, --notes or --prerelease"); |
| 2200 |
} |
| 2201 |
let edit = hub_api::ReleaseEdit { title, notes, prerelease }; |
| 2202 |
let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?; |
| 2203 |
if json { |
| 2204 |
println!("{}", serde_json::to_string(&r)?); |
| 2205 |
} else { |
| 2206 |
println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); |
| 2207 |
} |
| 2208 |
} |
| 2209 |
ReleaseCmd::Upload { tag, files } => { |
| 2210 |
if files.is_empty() { |
| 2211 |
bail!("name the files to attach"); |
| 2212 |
} |
| 2213 |
for f in files { |
| 2214 |
let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string(); |
| 2215 |
let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?; |
| 2216 |
c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?; |
| 2217 |
println!("{} attached {name} to {tag}", ui::ok("✔")); |
| 2218 |
} |
| 2219 |
} |
| 2220 |
ReleaseCmd::Trust { tag } => { |
| 2221 |
let path = format!("{base}/releases/trust/{}", enc(&tag)); |
| 2222 |
if json { |
| 2223 |
println!("{}", c.get_text(&path)?); |
| 2224 |
return Ok(0); |
| 2225 |
} |
| 2226 |
let r: serde_json::Value = c.get(&path)?; |
| 2227 |
println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"]))); |
| 2228 |
let mut worst = 0; |
| 2229 |
for ch in r["audit"].as_array().into_iter().flatten() { |
| 2230 |
let v = ch["verdict"].as_str().unwrap_or(""); |
| 2231 |
worst = worst.max(match v { |
| 2232 |
"fail" => 2, |
| 2233 |
"warn" => 1, |
| 2234 |
_ => 0, |
| 2235 |
}); |
| 2236 |
let g = match v { |
| 2237 |
"pass" => ui::ok("✔"), |
| 2238 |
"warn" => ui::warn("!"), |
| 2239 |
_ => ui::bad("✘"), |
| 2240 |
}; |
| 2241 |
println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or(""))); |
| 2242 |
} |
| 2243 |
return Ok(if worst == 2 { 1 } else { 0 }); |
| 2244 |
} |
| 2245 |
} |
| 2246 |
Ok(0) |
| 2247 |
} |
| 2248 |
|
| 2249 |
#[cfg(test)] |
| 2250 |
mod tests { |
| 2251 |
|
| 2252 |
#[test] |
| 2253 |
fn runner_update_scopes_resolve_by_name_or_id() { |
| 2254 |
let all = hub_api::RunnerUpdates { |
| 2255 |
repo: String::new(), |
| 2256 |
settings: vec![], |
| 2257 |
groups: vec![hub_api::RunnerGroup { id: 4, owner: "acme".into(), name: "canary".into(), percent: None, members: vec![] }], |
| 2258 |
runners: vec![], |
| 2259 |
holds: vec![], |
| 2260 |
}; |
| 2261 |
assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new())); |
| 2262 |
assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string())); |
| 2263 |
for g in ["group:canary", "group:acme/canary", "group:4"] { |
| 2264 |
assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}"); |
| 2265 |
} |
| 2266 |
assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner")); |
| 2267 |
assert!(update_scope("everyone", &all).is_err()); |
| 2268 |
assert_eq!(switch(Some("inherit")).unwrap(), Some(None)); |
| 2269 |
assert!(switch(Some("yes")).is_err()); |
| 2270 |
} |
| 2271 |
use super::*; |
| 2272 |
|
| 2273 |
|
| 2274 |
|
| 2275 |
#[test] |
| 2276 |
fn drop_commands_parse() { |
| 2277 |
let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap(); |
| 2278 |
match cli.cmd { |
| 2279 |
Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => { |
| 2280 |
assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]); |
| 2281 |
assert!(secret); |
| 2282 |
assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes"))); |
| 2283 |
} |
| 2284 |
_ => panic!("not drop create"), |
| 2285 |
} |
| 2286 |
assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file"); |
| 2287 |
match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() { |
| 2288 |
Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => { |
| 2289 |
assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05"))); |
| 2290 |
assert!(channel.is_none() && dry_run.is_none()); |
| 2291 |
} |
| 2292 |
_ => panic!("not runner-updates set"), |
| 2293 |
} |
| 2294 |
assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None })); |
| 2295 |
match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() { |
| 2296 |
Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)), |
| 2297 |
_ => panic!("not drop list"), |
| 2298 |
} |
| 2299 |
match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd { |
| 2300 |
Cmd::Drop { cmd: DropCmd::View { id, file } } => { |
| 2301 |
assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt"))) |
| 2302 |
} |
| 2303 |
_ => panic!("not drop view"), |
| 2304 |
} |
| 2305 |
assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } })); |
| 2306 |
assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567"); |
| 2307 |
assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567"); |
| 2308 |
assert!(drop_id("andy/notes").is_err()); |
| 2309 |
} |
| 2310 |
} |