| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
mod client; |
| 6 |
mod mcp; |
| 7 |
mod target; |
| 8 |
mod ui; |
| 9 |
|
| 10 |
use anyhow::{bail, Context, Result}; |
| 11 |
use clap::{Parser, Subcommand}; |
| 12 |
use client::Client; |
| 13 |
use hub_api::{ |
| 14 |
FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag, |
| 15 |
}; |
| 16 |
use std::time::Duration; |
| 17 |
use target::{Choice, Config, Target}; |
| 18 |
|
| 19 |
#[derive(Parser)] |
| 20 |
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")] |
| 21 |
struct Cli { |
| 22 |
|
| 23 |
#[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")] |
| 24 |
repo: Option<String>, |
| 25 |
|
| 26 |
#[arg(long, global = true, value_name = "URL")] |
| 27 |
hub: Option<String>, |
| 28 |
|
| 29 |
#[arg(long, global = true)] |
| 30 |
remote: Option<String>, |
| 31 |
|
| 32 |
#[arg(long, global = true)] |
| 33 |
json: bool, |
| 34 |
|
| 35 |
#[arg(long, global = true)] |
| 36 |
plain: bool, |
| 37 |
#[command(subcommand)] |
| 38 |
cmd: Cmd, |
| 39 |
} |
| 40 |
|
| 41 |
#[derive(Subcommand)] |
| 42 |
enum Cmd { |
| 43 |
|
| 44 |
Auth { |
| 45 |
#[command(subcommand)] |
| 46 |
cmd: AuthCmd, |
| 47 |
}, |
| 48 |
|
| 49 |
Repo { |
| 50 |
#[command(subcommand)] |
| 51 |
cmd: RepoCmd, |
| 52 |
}, |
| 53 |
|
| 54 |
Issue { |
| 55 |
#[command(subcommand)] |
| 56 |
cmd: IssueCmd, |
| 57 |
}, |
| 58 |
|
| 59 |
Proposal { |
| 60 |
#[command(subcommand)] |
| 61 |
cmd: ProposalCmd, |
| 62 |
}, |
| 63 |
|
| 64 |
Coverage { |
| 65 |
#[command(subcommand)] |
| 66 |
cmd: CoverageCmd, |
| 67 |
}, |
| 68 |
|
| 69 |
Run { |
| 70 |
#[command(subcommand)] |
| 71 |
cmd: RunCmd, |
| 72 |
}, |
| 73 |
|
| 74 |
Report { |
| 75 |
#[command(subcommand)] |
| 76 |
cmd: ReportCmd, |
| 77 |
}, |
| 78 |
|
| 79 |
Release { |
| 80 |
#[command(subcommand)] |
| 81 |
cmd: ReleaseCmd, |
| 82 |
}, |
| 83 |
|
| 84 |
Tag { |
| 85 |
#[command(subcommand)] |
| 86 |
cmd: TagCmd, |
| 87 |
}, |
| 88 |
|
| 89 |
Label { |
| 90 |
#[command(subcommand)] |
| 91 |
cmd: LabelCmd, |
| 92 |
}, |
| 93 |
|
| 94 |
Milestone { |
| 95 |
#[command(subcommand)] |
| 96 |
cmd: MilestoneCmd, |
| 97 |
}, |
| 98 |
|
| 99 |
|
| 100 |
Project { |
| 101 |
#[command(subcommand)] |
| 102 |
cmd: ProjectCmd, |
| 103 |
|
| 104 |
#[arg(long, global = true)] |
| 105 |
owner: Option<String>, |
| 106 |
}, |
| 107 |
|
| 108 |
|
| 109 |
Assistant { |
| 110 |
#[command(subcommand)] |
| 111 |
cmd: AssistantCmd, |
| 112 |
|
| 113 |
#[arg(long, global = true)] |
| 114 |
org: Option<String>, |
| 115 |
|
| 116 |
#[arg(long, global = true, conflicts_with = "org")] |
| 117 |
site: bool, |
| 118 |
}, |
| 119 |
|
| 120 |
|
| 121 |
Agent { |
| 122 |
#[command(subcommand)] |
| 123 |
cmd: AgentCmd, |
| 124 |
}, |
| 125 |
|
| 126 |
|
| 127 |
Drop { |
| 128 |
#[command(subcommand)] |
| 129 |
cmd: DropCmd, |
| 130 |
}, |
| 131 |
|
| 132 |
|
| 133 |
#[command(name = "runner-updates")] |
| 134 |
RunnerUpdates { |
| 135 |
#[command(subcommand)] |
| 136 |
cmd: Option<RunnerUpdatesCmd>, |
| 137 |
}, |
| 138 |
|
| 139 |
Mcp { |
| 140 |
|
| 141 |
#[arg(long)] |
| 142 |
allow_write: bool, |
| 143 |
}, |
| 144 |
|
| 145 |
Api { |
| 146 |
|
| 147 |
path: String, |
| 148 |
|
| 149 |
#[arg(long, short = 'X', default_value = "GET")] |
| 150 |
method: String, |
| 151 |
|
| 152 |
#[arg(long, short = 'd')] |
| 153 |
data: Option<String>, |
| 154 |
}, |
| 155 |
} |
| 156 |
|
| 157 |
#[derive(Subcommand)] |
| 158 |
enum AgentCmd { |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
Grant { |
| 164 |
|
| 165 |
name: String, |
| 166 |
|
| 167 |
#[arg(long, default_value = "changes,seal,refs")] |
| 168 |
scope: String, |
| 169 |
|
| 170 |
#[arg(long = "for", value_name = "DURATION", default_value = "30d")] |
| 171 |
lasts: String, |
| 172 |
}, |
| 173 |
|
| 174 |
List, |
| 175 |
|
| 176 |
Revoke { id: i64 }, |
| 177 |
} |
| 178 |
|
| 179 |
#[derive(Subcommand)] |
| 180 |
enum DropCmd { |
| 181 |
|
| 182 |
Create { |
| 183 |
|
| 184 |
#[arg(required = true)] |
| 185 |
files: Vec<std::path::PathBuf>, |
| 186 |
|
| 187 |
#[arg(long)] |
| 188 |
secret: bool, |
| 189 |
|
| 190 |
#[arg(long, short = 'd', value_name = "TEXT")] |
| 191 |
description: Option<String>, |
| 192 |
|
| 193 |
#[arg(long, short = 't')] |
| 194 |
title: Option<String>, |
| 195 |
}, |
| 196 |
|
| 197 |
List { |
| 198 |
|
| 199 |
#[arg(long, short = 'u', value_name = "NAME")] |
| 200 |
user: Option<String>, |
| 201 |
}, |
| 202 |
|
| 203 |
View { |
| 204 |
|
| 205 |
id: String, |
| 206 |
|
| 207 |
#[arg(long, short = 'f', value_name = "NAME")] |
| 208 |
file: Option<String>, |
| 209 |
}, |
| 210 |
|
| 211 |
Delete { |
| 212 |
|
| 213 |
id: String, |
| 214 |
}, |
| 215 |
|
| 216 |
Fork { |
| 217 |
|
| 218 |
id: String, |
| 219 |
}, |
| 220 |
|
| 221 |
Star { |
| 222 |
|
| 223 |
id: String, |
| 224 |
}, |
| 225 |
|
| 226 |
Unstar { |
| 227 |
|
| 228 |
id: String, |
| 229 |
}, |
| 230 |
|
| 231 |
Comments { |
| 232 |
|
| 233 |
id: String, |
| 234 |
}, |
| 235 |
|
| 236 |
Comment { |
| 237 |
|
| 238 |
id: String, |
| 239 |
|
| 240 |
#[arg(long, short = 'm')] |
| 241 |
message: String, |
| 242 |
}, |
| 243 |
} |
| 244 |
|
| 245 |
#[derive(Subcommand)] |
| 246 |
enum RunnerUpdatesCmd { |
| 247 |
|
| 248 |
Show, |
| 249 |
|
| 250 |
Set { |
| 251 |
|
| 252 |
scope: String, |
| 253 |
|
| 254 |
#[arg(long)] |
| 255 |
updates: Option<String>, |
| 256 |
|
| 257 |
#[arg(long)] |
| 258 |
channel: Option<String>, |
| 259 |
|
| 260 |
#[arg(long)] |
| 261 |
window: Option<String>, |
| 262 |
|
| 263 |
#[arg(long)] |
| 264 |
dry_run: Option<String>, |
| 265 |
}, |
| 266 |
|
| 267 |
Lift { version: String }, |
| 268 |
} |
| 269 |
|
| 270 |
#[derive(Subcommand)] |
| 271 |
enum AuthCmd { |
| 272 |
|
| 273 |
|
| 274 |
Login { |
| 275 |
|
| 276 |
#[arg(long = "with-hub", value_name = "URL")] |
| 277 |
url: String, |
| 278 |
|
| 279 |
|
| 280 |
#[arg(long)] |
| 281 |
token: Option<String>, |
| 282 |
|
| 283 |
#[arg(long)] |
| 284 |
ca: Option<std::path::PathBuf>, |
| 285 |
}, |
| 286 |
|
| 287 |
Status, |
| 288 |
} |
| 289 |
|
| 290 |
#[derive(Subcommand)] |
| 291 |
enum RepoCmd { |
| 292 |
|
| 293 |
View, |
| 294 |
} |
| 295 |
|
| 296 |
#[derive(Subcommand)] |
| 297 |
enum IssueCmd { |
| 298 |
|
| 299 |
Label(LabelChange), |
| 300 |
|
| 301 |
List { |
| 302 |
#[arg(long, default_value = "open")] |
| 303 |
state: String, |
| 304 |
}, |
| 305 |
|
| 306 |
View { number: i64 }, |
| 307 |
|
| 308 |
Create { |
| 309 |
#[arg(long, short)] |
| 310 |
title: String, |
| 311 |
#[arg(long, short)] |
| 312 |
body: Option<String>, |
| 313 |
|
| 314 |
#[arg(long, short = 'F')] |
| 315 |
body_file: Option<String>, |
| 316 |
|
| 317 |
#[arg(long, short)] |
| 318 |
label: Vec<String>, |
| 319 |
|
| 320 |
#[arg(long, short)] |
| 321 |
project: Option<i64>, |
| 322 |
|
| 323 |
#[arg(long, requires = "project")] |
| 324 |
column: Option<String>, |
| 325 |
|
| 326 |
#[arg(long, short = 'a', value_name = "FILE")] |
| 327 |
attach: Vec<std::path::PathBuf>, |
| 328 |
}, |
| 329 |
|
| 330 |
Close { |
| 331 |
number: i64, |
| 332 |
|
| 333 |
#[arg(long, default_value = "completed")] |
| 334 |
reason: String, |
| 335 |
#[command(flatten)] |
| 336 |
comment: StateComment, |
| 337 |
}, |
| 338 |
|
| 339 |
Reopen { |
| 340 |
number: i64, |
| 341 |
#[command(flatten)] |
| 342 |
comment: StateComment, |
| 343 |
}, |
| 344 |
|
| 345 |
|
| 346 |
Edit { |
| 347 |
number: i64, |
| 348 |
#[arg(long, short)] |
| 349 |
title: Option<String>, |
| 350 |
#[arg(long, short)] |
| 351 |
body: Option<String>, |
| 352 |
|
| 353 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 354 |
body_file: Option<String>, |
| 355 |
|
| 356 |
#[arg(long, short)] |
| 357 |
label: Vec<String>, |
| 358 |
|
| 359 |
#[arg(long, conflicts_with = "label")] |
| 360 |
no_labels: bool, |
| 361 |
|
| 362 |
#[arg(long, short)] |
| 363 |
assignee: Vec<String>, |
| 364 |
|
| 365 |
#[arg(long, conflicts_with = "assignee")] |
| 366 |
no_assignees: bool, |
| 367 |
|
| 368 |
#[arg(long, short)] |
| 369 |
milestone: Option<String>, |
| 370 |
}, |
| 371 |
|
| 372 |
Comment { |
| 373 |
number: i64, |
| 374 |
#[arg(long, short)] |
| 375 |
body: Option<String>, |
| 376 |
|
| 377 |
|
| 378 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 379 |
body_file: Option<String>, |
| 380 |
|
| 381 |
#[arg(long, short = 'a', value_name = "FILE")] |
| 382 |
attach: Vec<std::path::PathBuf>, |
| 383 |
}, |
| 384 |
} |
| 385 |
|
| 386 |
#[derive(Subcommand)] |
| 387 |
enum ProposalCmd { |
| 388 |
|
| 389 |
List { |
| 390 |
#[arg(long, default_value = "open")] |
| 391 |
state: String, |
| 392 |
|
| 393 |
#[arg(long, default_value_t = 30)] |
| 394 |
limit: usize, |
| 395 |
}, |
| 396 |
|
| 397 |
View { number: i64 }, |
| 398 |
|
| 399 |
Create { |
| 400 |
#[arg(long, short)] |
| 401 |
title: String, |
| 402 |
#[arg(long, short)] |
| 403 |
body: Option<String>, |
| 404 |
|
| 405 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 406 |
body_file: Option<String>, |
| 407 |
|
| 408 |
#[arg(long)] |
| 409 |
from: String, |
| 410 |
|
| 411 |
#[arg(long)] |
| 412 |
into: Option<String>, |
| 413 |
#[arg(long)] |
| 414 |
draft: bool, |
| 415 |
}, |
| 416 |
|
| 417 |
Edit { |
| 418 |
number: i64, |
| 419 |
#[arg(long, short)] |
| 420 |
title: Option<String>, |
| 421 |
#[arg(long, short)] |
| 422 |
body: Option<String>, |
| 423 |
|
| 424 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 425 |
body_file: Option<String>, |
| 426 |
}, |
| 427 |
|
| 428 |
Label(LabelChange), |
| 429 |
|
| 430 |
Comment { |
| 431 |
number: i64, |
| 432 |
#[arg(long, short)] |
| 433 |
body: Option<String>, |
| 434 |
|
| 435 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 436 |
body_file: Option<String>, |
| 437 |
}, |
| 438 |
|
| 439 |
Checks { number: i64 }, |
| 440 |
|
| 441 |
Land { |
| 442 |
number: i64, |
| 443 |
|
| 444 |
|
| 445 |
#[arg(long, value_name = "REASON", conflicts_with = "when_ready")] |
| 446 |
over_checks: Option<String>, |
| 447 |
|
| 448 |
#[arg(long)] |
| 449 |
when_ready: bool, |
| 450 |
|
| 451 |
#[arg(long, requires = "when_ready")] |
| 452 |
off: bool, |
| 453 |
}, |
| 454 |
|
| 455 |
Close { |
| 456 |
number: i64, |
| 457 |
|
| 458 |
#[arg(long, short = 'm')] |
| 459 |
message: Option<String>, |
| 460 |
}, |
| 461 |
|
| 462 |
Reopen { number: i64 }, |
| 463 |
|
| 464 |
Ready { |
| 465 |
number: i64, |
| 466 |
|
| 467 |
#[arg(long)] |
| 468 |
undo: bool, |
| 469 |
}, |
| 470 |
} |
| 471 |
|
| 472 |
#[derive(Subcommand)] |
| 473 |
enum AssistantCmd { |
| 474 |
|
| 475 |
List, |
| 476 |
|
| 477 |
Add { |
| 478 |
|
| 479 |
#[arg(long, default_value = "")] |
| 480 |
name: String, |
| 481 |
|
| 482 |
#[arg(long, default_value = "")] |
| 483 |
preset: String, |
| 484 |
|
| 485 |
#[arg(long, default_value = "")] |
| 486 |
endpoint: String, |
| 487 |
|
| 488 |
#[arg(long, default_value = "")] |
| 489 |
api: String, |
| 490 |
|
| 491 |
#[arg(long)] |
| 492 |
model: String, |
| 493 |
|
| 494 |
#[arg(long, value_name = "VAR")] |
| 495 |
token_env: Option<String>, |
| 496 |
|
| 497 |
#[arg(long)] |
| 498 |
off: bool, |
| 499 |
}, |
| 500 |
|
| 501 |
Remove { name: String }, |
| 502 |
|
| 503 |
Prompt { |
| 504 |
|
| 505 |
#[arg(long, value_name = "FILE")] |
| 506 |
set: Option<std::path::PathBuf>, |
| 507 |
}, |
| 508 |
} |
| 509 |
|
| 510 |
#[derive(Subcommand)] |
| 511 |
enum LabelCmd { |
| 512 |
|
| 513 |
List, |
| 514 |
|
| 515 |
Create { |
| 516 |
name: String, |
| 517 |
|
| 518 |
#[arg(long)] |
| 519 |
colour: Option<String>, |
| 520 |
#[arg(long, short, default_value = "")] |
| 521 |
description: String, |
| 522 |
}, |
| 523 |
|
| 524 |
Delete { name: String }, |
| 525 |
} |
| 526 |
|
| 527 |
#[derive(Subcommand)] |
| 528 |
enum ProjectCmd { |
| 529 |
|
| 530 |
List, |
| 531 |
|
| 532 |
View { |
| 533 |
number: i64, |
| 534 |
|
| 535 |
#[arg(long)] |
| 536 |
archived: bool, |
| 537 |
|
| 538 |
|
| 539 |
#[arg(long, short = 'q', conflicts_with = "view")] |
| 540 |
filter: Option<String>, |
| 541 |
|
| 542 |
#[arg(long)] |
| 543 |
view: Option<String>, |
| 544 |
}, |
| 545 |
|
| 546 |
Create { |
| 547 |
title: String, |
| 548 |
#[arg(long, short, default_value = "")] |
| 549 |
description: String, |
| 550 |
|
| 551 |
#[arg(long)] |
| 552 |
private: bool, |
| 553 |
}, |
| 554 |
|
| 555 |
Close { number: i64 }, |
| 556 |
|
| 557 |
Reopen { number: i64 }, |
| 558 |
|
| 559 |
|
| 560 |
Transfer { |
| 561 |
number: i64, |
| 562 |
|
| 563 |
#[arg(long)] |
| 564 |
to: String, |
| 565 |
}, |
| 566 |
|
| 567 |
Card { |
| 568 |
#[command(subcommand)] |
| 569 |
cmd: CardCmd, |
| 570 |
}, |
| 571 |
|
| 572 |
|
| 573 |
Charts { |
| 574 |
|
| 575 |
number: i64, |
| 576 |
|
| 577 |
#[arg(long, short = 'q')] |
| 578 |
filter: Option<String>, |
| 579 |
}, |
| 580 |
|
| 581 |
Column { |
| 582 |
#[command(subcommand)] |
| 583 |
cmd: ColumnCmd, |
| 584 |
}, |
| 585 |
} |
| 586 |
|
| 587 |
#[derive(Subcommand)] |
| 588 |
enum ColumnCmd { |
| 589 |
|
| 590 |
Add { |
| 591 |
|
| 592 |
number: i64, |
| 593 |
name: String, |
| 594 |
}, |
| 595 |
|
| 596 |
Rename { |
| 597 |
|
| 598 |
number: i64, |
| 599 |
column: String, |
| 600 |
|
| 601 |
to: String, |
| 602 |
}, |
| 603 |
|
| 604 |
Move { |
| 605 |
|
| 606 |
number: i64, |
| 607 |
column: String, |
| 608 |
|
| 609 |
#[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])] |
| 610 |
to: Option<i64>, |
| 611 |
|
| 612 |
#[arg(long, conflicts_with = "right")] |
| 613 |
left: bool, |
| 614 |
|
| 615 |
#[arg(long)] |
| 616 |
right: bool, |
| 617 |
}, |
| 618 |
|
| 619 |
Remove { |
| 620 |
|
| 621 |
number: i64, |
| 622 |
column: String, |
| 623 |
}, |
| 624 |
} |
| 625 |
|
| 626 |
#[derive(Subcommand)] |
| 627 |
enum CardCmd { |
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
Add { |
| 632 |
number: i64, |
| 633 |
|
| 634 |
reference: Option<String>, |
| 635 |
|
| 636 |
#[arg(long, conflicts_with = "reference")] |
| 637 |
note: Option<String>, |
| 638 |
|
| 639 |
#[arg(long, short)] |
| 640 |
column: Option<String>, |
| 641 |
}, |
| 642 |
|
| 643 |
|
| 644 |
Move { |
| 645 |
number: i64, |
| 646 |
|
| 647 |
card: Option<i64>, |
| 648 |
#[arg(long, short)] |
| 649 |
column: String, |
| 650 |
|
| 651 |
#[arg(long, conflicts_with = "card")] |
| 652 |
from: Option<String>, |
| 653 |
|
| 654 |
#[arg(long, value_delimiter = ',', requires = "from")] |
| 655 |
except: Vec<String>, |
| 656 |
|
| 657 |
#[arg(long, value_delimiter = ',', requires = "from")] |
| 658 |
state: Vec<String>, |
| 659 |
|
| 660 |
#[arg(long, requires = "from")] |
| 661 |
dry_run: bool, |
| 662 |
}, |
| 663 |
|
| 664 |
Archive { |
| 665 |
number: i64, |
| 666 |
|
| 667 |
#[arg(long)] |
| 668 |
from: String, |
| 669 |
|
| 670 |
#[arg(long)] |
| 671 |
older: Option<String>, |
| 672 |
|
| 673 |
#[arg(long, value_delimiter = ',')] |
| 674 |
except: Vec<String>, |
| 675 |
|
| 676 |
#[arg(long, value_delimiter = ',')] |
| 677 |
state: Vec<String>, |
| 678 |
|
| 679 |
#[arg(long)] |
| 680 |
dry_run: bool, |
| 681 |
}, |
| 682 |
|
| 683 |
Restore { number: i64, card: i64 }, |
| 684 |
|
| 685 |
Remove { number: i64, card: i64 }, |
| 686 |
} |
| 687 |
|
| 688 |
#[derive(Subcommand)] |
| 689 |
enum MilestoneCmd { |
| 690 |
|
| 691 |
List, |
| 692 |
|
| 693 |
Create { |
| 694 |
title: String, |
| 695 |
#[arg(long, short, default_value = "")] |
| 696 |
description: String, |
| 697 |
|
| 698 |
#[arg(long)] |
| 699 |
due: Option<String>, |
| 700 |
}, |
| 701 |
|
| 702 |
Edit { |
| 703 |
title: String, |
| 704 |
#[arg(long, short)] |
| 705 |
rename: Option<String>, |
| 706 |
#[arg(long, short)] |
| 707 |
description: Option<String>, |
| 708 |
|
| 709 |
#[arg(long)] |
| 710 |
due: Option<String>, |
| 711 |
}, |
| 712 |
|
| 713 |
Close { title: String }, |
| 714 |
|
| 715 |
Reopen { title: String }, |
| 716 |
} |
| 717 |
|
| 718 |
|
| 719 |
#[derive(clap::Args)] |
| 720 |
struct LabelChange { |
| 721 |
number: i64, |
| 722 |
|
| 723 |
#[arg(long, short)] |
| 724 |
add: Vec<String>, |
| 725 |
|
| 726 |
#[arg(long, short)] |
| 727 |
remove: Vec<String>, |
| 728 |
} |
| 729 |
|
| 730 |
impl LabelChange { |
| 731 |
|
| 732 |
fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> { |
| 733 |
if self.add.is_empty() && self.remove.is_empty() { |
| 734 |
bail!("say what to change: --add NAME or --remove NAME"); |
| 735 |
} |
| 736 |
let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect(); |
| 737 |
for a in &self.add { |
| 738 |
if !names.contains(a) { |
| 739 |
names.push(a.clone()); |
| 740 |
} |
| 741 |
} |
| 742 |
Ok(names) |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
fn label_names(labels: &[String]) -> String { |
| 747 |
if labels.is_empty() { |
| 748 |
ui::dim("no labels") |
| 749 |
} else { |
| 750 |
labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ") |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
#[derive(Subcommand)] |
| 755 |
enum CoverageCmd { |
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
Upload { |
| 761 |
file: std::path::PathBuf, |
| 762 |
#[arg(long)] |
| 763 |
bookmark: Option<String>, |
| 764 |
|
| 765 |
#[arg(long, conflicts_with = "bookmark")] |
| 766 |
change: Option<String>, |
| 767 |
}, |
| 768 |
} |
| 769 |
|
| 770 |
#[derive(Subcommand)] |
| 771 |
enum RunCmd { |
| 772 |
|
| 773 |
List { |
| 774 |
#[arg(long, default_value_t = 20)] |
| 775 |
limit: i64, |
| 776 |
}, |
| 777 |
|
| 778 |
View { |
| 779 |
|
| 780 |
number: Option<i64>, |
| 781 |
|
| 782 |
#[arg(long, conflicts_with = "number")] |
| 783 |
bookmark: Option<String>, |
| 784 |
|
| 785 |
#[arg(long)] |
| 786 |
timings: bool, |
| 787 |
}, |
| 788 |
|
| 789 |
Start { |
| 790 |
#[arg(long)] |
| 791 |
bookmark: Option<String>, |
| 792 |
|
| 793 |
#[arg(long, conflicts_with = "bookmark")] |
| 794 |
change: Option<String>, |
| 795 |
|
| 796 |
#[arg(long = "job", value_name = "NAME")] |
| 797 |
jobs: Vec<String>, |
| 798 |
|
| 799 |
#[arg(long)] |
| 800 |
watch: bool, |
| 801 |
}, |
| 802 |
|
| 803 |
Watch { |
| 804 |
|
| 805 |
number: Option<i64>, |
| 806 |
|
| 807 |
#[arg(long, conflicts_with = "number")] |
| 808 |
bookmark: Option<String>, |
| 809 |
}, |
| 810 |
|
| 811 |
Log { number: i64, job: String }, |
| 812 |
|
| 813 |
Report { |
| 814 |
number: i64, |
| 815 |
job: String, |
| 816 |
#[command(flatten)] |
| 817 |
pick: ReportPick, |
| 818 |
}, |
| 819 |
|
| 820 |
|
| 821 |
Rerun { |
| 822 |
number: i64, |
| 823 |
#[arg(long)] |
| 824 |
job: Option<String>, |
| 825 |
}, |
| 826 |
|
| 827 |
Cancel { number: i64 }, |
| 828 |
|
| 829 |
Approve { |
| 830 |
number: i64, |
| 831 |
#[arg(long)] |
| 832 |
job: String, |
| 833 |
}, |
| 834 |
|
| 835 |
Reject { |
| 836 |
number: i64, |
| 837 |
#[arg(long)] |
| 838 |
job: String, |
| 839 |
}, |
| 840 |
} |
| 841 |
|
| 842 |
|
| 843 |
#[derive(clap::Args)] |
| 844 |
struct ReportPick { |
| 845 |
|
| 846 |
#[arg(long)] |
| 847 |
name: Option<String>, |
| 848 |
|
| 849 |
#[arg(long, conflicts_with = "file")] |
| 850 |
list: bool, |
| 851 |
|
| 852 |
#[arg(long, value_name = "PATH")] |
| 853 |
file: Option<String>, |
| 854 |
|
| 855 |
#[arg(long, short, value_name = "FILE", requires = "file")] |
| 856 |
output: Option<std::path::PathBuf>, |
| 857 |
} |
| 858 |
|
| 859 |
#[derive(Subcommand)] |
| 860 |
enum ReportCmd { |
| 861 |
|
| 862 |
List { |
| 863 |
|
| 864 |
#[arg(long)] |
| 865 |
bookmark: Option<String>, |
| 866 |
}, |
| 867 |
|
| 868 |
Show { |
| 869 |
report: String, |
| 870 |
#[arg(long, conflicts_with = "bookmark")] |
| 871 |
id: Option<i64>, |
| 872 |
#[arg(long)] |
| 873 |
bookmark: Option<String>, |
| 874 |
|
| 875 |
#[arg(long, conflicts_with = "file")] |
| 876 |
list: bool, |
| 877 |
|
| 878 |
#[arg(long, value_name = "PATH")] |
| 879 |
file: Option<String>, |
| 880 |
|
| 881 |
#[arg(long, short, value_name = "FILE", requires = "file")] |
| 882 |
output: Option<std::path::PathBuf>, |
| 883 |
}, |
| 884 |
} |
| 885 |
|
| 886 |
#[derive(Subcommand)] |
| 887 |
enum TagCmd { |
| 888 |
|
| 889 |
List, |
| 890 |
|
| 891 |
|
| 892 |
Create { |
| 893 |
name: String, |
| 894 |
|
| 895 |
#[arg(long)] |
| 896 |
target: Option<String>, |
| 897 |
#[arg(long, short)] |
| 898 |
message: Option<String>, |
| 899 |
}, |
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
Delete { |
| 904 |
name: String, |
| 905 |
|
| 906 |
#[arg(long, short)] |
| 907 |
reason: Option<String>, |
| 908 |
}, |
| 909 |
} |
| 910 |
|
| 911 |
#[derive(Subcommand)] |
| 912 |
enum ReleaseCmd { |
| 913 |
|
| 914 |
List, |
| 915 |
|
| 916 |
Create { |
| 917 |
tag: String, |
| 918 |
#[arg(long, short)] |
| 919 |
title: Option<String>, |
| 920 |
|
| 921 |
#[arg(long, short)] |
| 922 |
notes: Option<String>, |
| 923 |
#[arg(long)] |
| 924 |
prerelease: bool, |
| 925 |
}, |
| 926 |
|
| 927 |
Edit { |
| 928 |
tag: String, |
| 929 |
#[arg(long, short)] |
| 930 |
title: Option<String>, |
| 931 |
|
| 932 |
#[arg(long, short)] |
| 933 |
notes: Option<String>, |
| 934 |
|
| 935 |
#[arg(long)] |
| 936 |
prerelease: Option<bool>, |
| 937 |
}, |
| 938 |
|
| 939 |
Upload { tag: String, files: Vec<std::path::PathBuf> }, |
| 940 |
|
| 941 |
Trust { tag: String }, |
| 942 |
} |
| 943 |
|
| 944 |
fn main() { |
| 945 |
|
| 946 |
|
| 947 |
|
| 948 |
#[cfg(unix)] |
| 949 |
unsafe { |
| 950 |
libc::signal(libc::SIGPIPE, libc::SIG_DFL); |
| 951 |
} |
| 952 |
let cli = Cli::parse(); |
| 953 |
ui::init(cli.plain); |
| 954 |
match run(cli) { |
| 955 |
Ok(code) => std::process::exit(code), |
| 956 |
Err(e) => { |
| 957 |
eprintln!("{} {e:#}", ui::bad("error:")); |
| 958 |
std::process::exit(2); |
| 959 |
} |
| 960 |
} |
| 961 |
} |
| 962 |
|
| 963 |
fn enc(s: &str) -> String { |
| 964 |
let mut out = String::new(); |
| 965 |
for b in s.bytes() { |
| 966 |
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { |
| 967 |
out.push(b as char); |
| 968 |
} else { |
| 969 |
out.push_str(&format!("%{b:02X}")); |
| 970 |
} |
| 971 |
} |
| 972 |
out |
| 973 |
} |
| 974 |
|
| 975 |
fn run(cli: Cli) -> Result<i32> { |
| 976 |
let cfg = Config::load()?; |
| 977 |
if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd { |
| 978 |
return login(cfg, url, token.clone(), ca.clone()); |
| 979 |
} |
| 980 |
let here = std::env::current_dir()?; |
| 981 |
let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?; |
| 982 |
let c = Client::new(&t)?; |
| 983 |
let json = cli.json; |
| 984 |
match cli.cmd { |
| 985 |
Cmd::Auth { cmd: AuthCmd::Status } => { |
| 986 |
let me: serde_json::Value = c.get("/user")?; |
| 987 |
if json { |
| 988 |
println!("{me}"); |
| 989 |
} else { |
| 990 |
println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?"))); |
| 991 |
} |
| 992 |
Ok(0) |
| 993 |
} |
| 994 |
Cmd::Auth { .. } => unreachable!(), |
| 995 |
Cmd::Mcp { allow_write } => { |
| 996 |
t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?; |
| 997 |
mcp::serve(c, t, allow_write) |
| 998 |
} |
| 999 |
Cmd::Api { path, method, data } => { |
| 1000 |
let path = if path.starts_with('/') { path } else { format!("/{path}") }; |
| 1001 |
let text = match data { |
| 1002 |
Some(d) => c.send_text( |
| 1003 |
&method.to_uppercase(), |
| 1004 |
&path, |
| 1005 |
&serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?, |
| 1006 |
)?, |
| 1007 |
None => c.get_text(&path)?, |
| 1008 |
}; |
| 1009 |
println!("{text}"); |
| 1010 |
Ok(0) |
| 1011 |
} |
| 1012 |
Cmd::Repo { cmd: RepoCmd::View } => { |
| 1013 |
let path = t.repo_path()?; |
| 1014 |
if json { |
| 1015 |
println!("{}", c.get_text(&path)?); |
| 1016 |
return Ok(0); |
| 1017 |
} |
| 1018 |
let r: serde_json::Value = c.get(&path)?; |
| 1019 |
println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or(""))); |
| 1020 |
if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) { |
| 1021 |
println!("{d}"); |
| 1022 |
} |
| 1023 |
println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or(""))); |
| 1024 |
println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name))); |
| 1025 |
Ok(0) |
| 1026 |
} |
| 1027 |
Cmd::Issue { cmd } => issue(&c, &t, cmd, json), |
| 1028 |
Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json), |
| 1029 |
Cmd::Run { cmd } => flow(&c, &t, cmd, json), |
| 1030 |
Cmd::Report { cmd } => report(&c, &t, cmd, json), |
| 1031 |
Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => { |
| 1032 |
let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?; |
| 1033 |
let mut body = serde_json::json!({ "content": content }); |
| 1034 |
if let Some(b) = bookmark { |
| 1035 |
body["bookmark"] = b.into(); |
| 1036 |
} |
| 1037 |
if let Some(ch) = change { |
| 1038 |
body["change"] = ch.into(); |
| 1039 |
} |
| 1040 |
let base = t.repo_path()?; |
| 1041 |
let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?; |
| 1042 |
if json { |
| 1043 |
println!("{}", serde_json::to_string(&r)?); |
| 1044 |
} else { |
| 1045 |
let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into()); |
| 1046 |
let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() }; |
| 1047 |
println!( |
| 1048 |
"{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}", |
| 1049 |
ui::ok("✔"), |
| 1050 |
r.lines_hit, |
| 1051 |
r.lines_found, |
| 1052 |
r.files, |
| 1053 |
ui::dim(&r.url) |
| 1054 |
); |
| 1055 |
if r.dropped > 0 { |
| 1056 |
println!(" {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped))); |
| 1057 |
} |
| 1058 |
} |
| 1059 |
Ok(0) |
| 1060 |
} |
| 1061 |
Cmd::Release { cmd } => release(&c, &t, cmd, json), |
| 1062 |
Cmd::Tag { cmd } => tag(&c, &t, cmd, json), |
| 1063 |
Cmd::Label { cmd } => label(&c, &t, cmd, json), |
| 1064 |
Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json), |
| 1065 |
Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json), |
| 1066 |
Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json), |
| 1067 |
Cmd::Agent { cmd } => agent(&c, cmd, json), |
| 1068 |
Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json), |
| 1069 |
Cmd::Drop { cmd } => drop_cmd(&c, cmd, json), |
| 1070 |
} |
| 1071 |
} |
| 1072 |
|
| 1073 |
|
| 1074 |
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> { |
| 1075 |
Ok(match v { |
| 1076 |
None => None, |
| 1077 |
Some("on") => Some(Some(true)), |
| 1078 |
Some("off") => Some(Some(false)), |
| 1079 |
Some("inherit") => Some(None), |
| 1080 |
Some(other) => bail!("{other:?}: say on, off or inherit"), |
| 1081 |
}) |
| 1082 |
} |
| 1083 |
|
| 1084 |
|
| 1085 |
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> { |
| 1086 |
let (kind, name) = scope.split_once(':').unwrap_or((scope, "")); |
| 1087 |
Ok(match kind { |
| 1088 |
"site" if name.is_empty() => ("site".into(), String::new()), |
| 1089 |
"owner" if !name.is_empty() => ("owner".into(), name.into()), |
| 1090 |
"group" => { |
| 1091 |
let g = all |
| 1092 |
.groups |
| 1093 |
.iter() |
| 1094 |
.find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name) |
| 1095 |
.with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?; |
| 1096 |
("group".into(), g.id.to_string()) |
| 1097 |
} |
| 1098 |
"runner" => { |
| 1099 |
let r = all |
| 1100 |
.runners |
| 1101 |
.iter() |
| 1102 |
.find(|r| r.id.to_string() == name || r.name == name) |
| 1103 |
.with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?; |
| 1104 |
("runner".into(), r.id.to_string()) |
| 1105 |
} |
| 1106 |
_ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"), |
| 1107 |
}) |
| 1108 |
} |
| 1109 |
|
| 1110 |
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> { |
| 1111 |
let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?; |
| 1112 |
match cmd { |
| 1113 |
RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?), |
| 1114 |
RunnerUpdatesCmd::Show => { |
| 1115 |
println!( |
| 1116 |
"{} {}", |
| 1117 |
ui::strong("Builds from"), |
| 1118 |
if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() } |
| 1119 |
); |
| 1120 |
for h in &all.holds { |
| 1121 |
println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why); |
| 1122 |
} |
| 1123 |
for s in &all.settings { |
| 1124 |
let mut said = vec![]; |
| 1125 |
if let Some(u) = s.updates { |
| 1126 |
said.push(format!("updates {}", if u { "on" } else { "off" })); |
| 1127 |
} |
| 1128 |
if let Some(ch) = &s.channel { |
| 1129 |
said.push(format!("channel {ch}")); |
| 1130 |
} |
| 1131 |
if let Some(w) = &s.window { |
| 1132 |
said.push(format!("window {w} UTC")); |
| 1133 |
} |
| 1134 |
if let Some(d) = s.dry_run { |
| 1135 |
said.push(format!("dry run {}", if d { "on" } else { "off" })); |
| 1136 |
} |
| 1137 |
let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) }; |
| 1138 |
println!(" {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") }); |
| 1139 |
} |
| 1140 |
for g in &all.groups { |
| 1141 |
let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) }; |
| 1142 |
let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}")); |
| 1143 |
if let Some(w) = g.wave { |
| 1144 |
what.push_str(&format!(", wave {w}")); |
| 1145 |
} |
| 1146 |
println!( |
| 1147 |
" group {} ({what}): {}", |
| 1148 |
ui::strong(&g.name), |
| 1149 |
if g.members.is_empty() { "none".into() } else { g.members.join(", ") } |
| 1150 |
); |
| 1151 |
} |
| 1152 |
for r in &all.runners { |
| 1153 |
let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") }; |
| 1154 |
println!(" {:<16} flow {:<22} {} ({}) {}", r.name, r.version, on, r.from[0], ui::dim(&r.now)); |
| 1155 |
} |
| 1156 |
} |
| 1157 |
RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => { |
| 1158 |
let (scope, key) = update_scope(&scope, &all)?; |
| 1159 |
let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting { |
| 1160 |
scope: scope.clone(), |
| 1161 |
key: key.clone(), |
| 1162 |
..Default::default() |
| 1163 |
}); |
| 1164 |
if let Some(u) = switch(updates.as_deref())? { |
| 1165 |
s.updates = u; |
| 1166 |
} |
| 1167 |
if let Some(d) = switch(dry_run.as_deref())? { |
| 1168 |
s.dry_run = d; |
| 1169 |
} |
| 1170 |
if let Some(ch) = channel { |
| 1171 |
s.channel = Some(ch).filter(|c| c != "inherit"); |
| 1172 |
} |
| 1173 |
if let Some(w) = window { |
| 1174 |
s.window = Some(w).filter(|w| w != "inherit"); |
| 1175 |
} |
| 1176 |
let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?; |
| 1177 |
println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved")); |
| 1178 |
} |
| 1179 |
RunnerUpdatesCmd::Lift { version } => { |
| 1180 |
c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?; |
| 1181 |
println!("{} flow {version} is offered again where the settings say so", ui::ok("✔")); |
| 1182 |
} |
| 1183 |
} |
| 1184 |
Ok(0) |
| 1185 |
} |
| 1186 |
|
| 1187 |
|
| 1188 |
fn drop_id(s: &str) -> Result<String> { |
| 1189 |
let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string(); |
| 1190 |
if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 1191 |
bail!("{s:?} is not a drop's id or address"); |
| 1192 |
} |
| 1193 |
Ok(id.to_ascii_lowercase()) |
| 1194 |
} |
| 1195 |
|
| 1196 |
fn drop_line(d: &hub_api::Drop) -> String { |
| 1197 |
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() }; |
| 1198 |
let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect(); |
| 1199 |
format!( |
| 1200 |
"{} {} {}{}", |
| 1201 |
ui::dim(&d.id), |
| 1202 |
ui::strong(&title), |
| 1203 |
if d.visibility == "secret" { ui::warn("secret ") } else { String::new() }, |
| 1204 |
ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms))) |
| 1205 |
) |
| 1206 |
} |
| 1207 |
|
| 1208 |
|
| 1209 |
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> { |
| 1210 |
let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?; |
| 1211 |
if json { |
| 1212 |
println!("{}", serde_json::to_string(&s)?); |
| 1213 |
} else { |
| 1214 |
println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars); |
| 1215 |
} |
| 1216 |
Ok(()) |
| 1217 |
} |
| 1218 |
|
| 1219 |
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> { |
| 1220 |
match cmd { |
| 1221 |
DropCmd::Create { files, secret, description, title } => { |
| 1222 |
let mut out = Vec::with_capacity(files.len()); |
| 1223 |
for f in &files { |
| 1224 |
let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?; |
| 1225 |
let content = |
| 1226 |
std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?; |
| 1227 |
out.push(hub_api::NewDropFile { name: name.to_string(), content }); |
| 1228 |
} |
| 1229 |
let new = |
| 1230 |
hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out }; |
| 1231 |
let d: hub_api::Drop = c.send("POST", "/drops", &new)?; |
| 1232 |
if json { |
| 1233 |
println!("{}", serde_json::to_string(&d)?); |
| 1234 |
} else { |
| 1235 |
println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url)); |
| 1236 |
println!(" {}", ui::dim(&format!("oxy clone {}", d.clone_url))); |
| 1237 |
} |
| 1238 |
} |
| 1239 |
DropCmd::List { user } => { |
| 1240 |
let path = match &user { |
| 1241 |
Some(u) => format!("/users/{}/drops", enc(u)), |
| 1242 |
None => "/drops".to_string(), |
| 1243 |
}; |
| 1244 |
if json { |
| 1245 |
println!("{}", c.get_text(&path)?); |
| 1246 |
return Ok(0); |
| 1247 |
} |
| 1248 |
let list: Vec<hub_api::Drop> = c.get(&path)?; |
| 1249 |
if list.is_empty() { |
| 1250 |
println!("{}", ui::dim("No drops.")); |
| 1251 |
} |
| 1252 |
for d in &list { |
| 1253 |
println!("{}", drop_line(d)); |
| 1254 |
} |
| 1255 |
} |
| 1256 |
DropCmd::View { id, file } => { |
| 1257 |
let path = format!("/drops/{}", drop_id(&id)?); |
| 1258 |
if json && file.is_none() { |
| 1259 |
println!("{}", c.get_text(&path)?); |
| 1260 |
return Ok(0); |
| 1261 |
} |
| 1262 |
let d: hub_api::Drop = c.get(&path)?; |
| 1263 |
if let Some(name) = file { |
| 1264 |
let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?; |
| 1265 |
let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?; |
| 1266 |
print!("{content}"); |
| 1267 |
return Ok(0); |
| 1268 |
} |
| 1269 |
println!("{}", drop_line(&d)); |
| 1270 |
if !d.description.is_empty() { |
| 1271 |
println!("{}", d.description); |
| 1272 |
} |
| 1273 |
println!("{}", ui::kv("url", &d.url)); |
| 1274 |
println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url))); |
| 1275 |
for f in &d.files { |
| 1276 |
println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size))); |
| 1277 |
match &f.content { |
| 1278 |
Some(text) => { |
| 1279 |
print!("{text}"); |
| 1280 |
if !text.ends_with('\n') && !text.is_empty() { |
| 1281 |
println!(); |
| 1282 |
} |
| 1283 |
} |
| 1284 |
None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))), |
| 1285 |
} |
| 1286 |
} |
| 1287 |
} |
| 1288 |
DropCmd::Delete { id } => { |
| 1289 |
let id = drop_id(&id)?; |
| 1290 |
c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?; |
| 1291 |
println!("{} drop {id}", ui::ok("✔ deleted")); |
| 1292 |
} |
| 1293 |
DropCmd::Fork { id } => { |
| 1294 |
let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?; |
| 1295 |
if json { |
| 1296 |
println!("{}", serde_json::to_string(&d)?); |
| 1297 |
} else { |
| 1298 |
println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url)); |
| 1299 |
} |
| 1300 |
} |
| 1301 |
DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?, |
| 1302 |
DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?, |
| 1303 |
DropCmd::Comments { id } => { |
| 1304 |
let path = format!("/drops/{}/comments", drop_id(&id)?); |
| 1305 |
if json { |
| 1306 |
println!("{}", c.get_text(&path)?); |
| 1307 |
return Ok(0); |
| 1308 |
} |
| 1309 |
let list: Vec<hub_api::DropComment> = c.get(&path)?; |
| 1310 |
if list.is_empty() { |
| 1311 |
println!("{}", ui::dim("No comments.")); |
| 1312 |
} |
| 1313 |
for m in &list { |
| 1314 |
println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms)))); |
| 1315 |
println!("{}\n", m.body); |
| 1316 |
} |
| 1317 |
} |
| 1318 |
DropCmd::Comment { id, message } => { |
| 1319 |
let m: hub_api::DropComment = |
| 1320 |
c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?; |
| 1321 |
if json { |
| 1322 |
println!("{}", serde_json::to_string(&m)?); |
| 1323 |
} else { |
| 1324 |
println!("{} commented (#{})", ui::ok("✔"), m.id); |
| 1325 |
} |
| 1326 |
} |
| 1327 |
} |
| 1328 |
Ok(0) |
| 1329 |
} |
| 1330 |
|
| 1331 |
|
| 1332 |
fn duration_ms(s: &str) -> Result<i64> { |
| 1333 |
let s = s.trim(); |
| 1334 |
let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())); |
| 1335 |
let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?; |
| 1336 |
let per = match unit { |
| 1337 |
"d" => 86_400_000, |
| 1338 |
"h" => 3_600_000, |
| 1339 |
"m" => 60_000, |
| 1340 |
_ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"), |
| 1341 |
}; |
| 1342 |
if n <= 0 { |
| 1343 |
bail!("a grant must last some time"); |
| 1344 |
} |
| 1345 |
Ok(n * per) |
| 1346 |
} |
| 1347 |
|
| 1348 |
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> { |
| 1349 |
use oxy_core::cert::{Grant, SignedGrant}; |
| 1350 |
use oxy_core::identity::{Identity, Scope}; |
| 1351 |
match cmd { |
| 1352 |
AgentCmd::Grant { name, scope, lasts } => { |
| 1353 |
let home = oxy_core::repo::default_home(); |
| 1354 |
let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| { |
| 1355 |
format!( |
| 1356 |
"{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell", |
| 1357 |
home.display() |
| 1358 |
) |
| 1359 |
})?; |
| 1360 |
let me: serde_json::Value = c.get("/user")?; |
| 1361 |
let username = me["username"].as_str().context("the hub did not say who you are")?; |
| 1362 |
let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?; |
| 1363 |
let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 1364 |
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; |
| 1365 |
let grant = Grant { |
| 1366 |
grantor: me_id.hash(), |
| 1367 |
subject: format!("agent:{name}@{username}"), |
| 1368 |
issuer: hub.hash(), |
| 1369 |
scope, |
| 1370 |
not_before: (now - 60_000) as u64, |
| 1371 |
expires: (now + duration_ms(&lasts)?) as u64, |
| 1372 |
}; |
| 1373 |
let signed = SignedGrant::sign(grant, &me_id, &sk); |
| 1374 |
let r: serde_json::Value = |
| 1375 |
c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?; |
| 1376 |
if json { |
| 1377 |
println!("{r}"); |
| 1378 |
return Ok(0); |
| 1379 |
} |
| 1380 |
println!( |
| 1381 |
"{} {} to act for you as {} ({}), until {}", |
| 1382 |
ui::ok("✔ granted"), |
| 1383 |
ui::strong(&name), |
| 1384 |
r["subject"].as_str().unwrap_or(""), |
| 1385 |
r["scope"].as_str().unwrap_or(""), |
| 1386 |
ui::date(r["expires_ms"].as_i64().unwrap_or(0)) |
| 1387 |
); |
| 1388 |
println!(" token (shown once): {}", r["token"].as_str().unwrap_or("")); |
| 1389 |
println!( |
| 1390 |
" {}", |
| 1391 |
ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless") |
| 1392 |
); |
| 1393 |
println!(" {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"]))); |
| 1394 |
Ok(0) |
| 1395 |
} |
| 1396 |
AgentCmd::List => { |
| 1397 |
let grants: Vec<serde_json::Value> = c.get("/agents/grants")?; |
| 1398 |
if json { |
| 1399 |
println!("{}", serde_json::to_string(&grants)?); |
| 1400 |
return Ok(0); |
| 1401 |
} |
| 1402 |
if grants.is_empty() { |
| 1403 |
println!("{}", ui::dim("no agent grants")); |
| 1404 |
} |
| 1405 |
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; |
| 1406 |
for g in grants { |
| 1407 |
let state = if g["revoked_ms"].is_i64() { |
| 1408 |
ui::bad("revoked") |
| 1409 |
} else if g["expires_ms"].as_i64().unwrap_or(0) <= now { |
| 1410 |
ui::dim("ended") |
| 1411 |
} else { |
| 1412 |
ui::ok("live") |
| 1413 |
}; |
| 1414 |
let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into()); |
| 1415 |
println!( |
| 1416 |
"#{:<4} {:<8} {} · {} · until {} · {}", |
| 1417 |
g["id"], |
| 1418 |
state, |
| 1419 |
ui::strong(g["subject"].as_str().unwrap_or("")), |
| 1420 |
g["scope"].as_str().unwrap_or(""), |
| 1421 |
ui::date(g["expires_ms"].as_i64().unwrap_or(0)), |
| 1422 |
ui::dim(&used) |
| 1423 |
); |
| 1424 |
} |
| 1425 |
Ok(0) |
| 1426 |
} |
| 1427 |
AgentCmd::Revoke { id } => { |
| 1428 |
c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?; |
| 1429 |
println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked")); |
| 1430 |
Ok(0) |
| 1431 |
} |
| 1432 |
} |
| 1433 |
} |
| 1434 |
|
| 1435 |
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> { |
| 1436 |
let hub = url.trim_end_matches('/').to_string(); |
| 1437 |
let token = match token.as_deref() { |
| 1438 |
Some("-") => { |
| 1439 |
eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:"); |
| 1440 |
let mut line = String::new(); |
| 1441 |
std::io::stdin().read_line(&mut line)?; |
| 1442 |
line.trim().to_string() |
| 1443 |
} |
| 1444 |
Some(t) => t.to_string(), |
| 1445 |
None => device_sign_in(&hub, ca.clone())?, |
| 1446 |
}; |
| 1447 |
if token.is_empty() { |
| 1448 |
bail!("no token given"); |
| 1449 |
} |
| 1450 |
let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() }; |
| 1451 |
let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?; |
| 1452 |
let account = me["username"].as_str().unwrap_or("?"); |
| 1453 |
|
| 1454 |
let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?; |
| 1455 |
let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c)); |
| 1456 |
oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 1457 |
cfg.default_hub = Some(hub.clone()); |
| 1458 |
cfg.save()?; |
| 1459 |
println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account)); |
| 1460 |
println!("{}", ui::dim(" oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it")); |
| 1461 |
Ok(0) |
| 1462 |
} |
| 1463 |
|
| 1464 |
|
| 1465 |
|
| 1466 |
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> { |
| 1467 |
let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() }; |
| 1468 |
let c = Client::new(&t)?; |
| 1469 |
let host = std::fs::read_to_string("/etc/hostname") |
| 1470 |
.ok() |
| 1471 |
.or_else(|| std::env::var("COMPUTERNAME").ok()) |
| 1472 |
.map(|h| h.trim().to_string()) |
| 1473 |
.filter(|h| !h.is_empty()); |
| 1474 |
let client = match host { |
| 1475 |
Some(h) => format!("oh on {h}"), |
| 1476 |
None => "oh".to_string(), |
| 1477 |
}; |
| 1478 |
let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"]; |
| 1479 |
let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?; |
| 1480 |
let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?; |
| 1481 |
if code != 200 { |
| 1482 |
bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body)); |
| 1483 |
} |
| 1484 |
let device = v["device_code"].as_str().context("no device code")?.to_string(); |
| 1485 |
let user = v["user_code"].as_str().unwrap_or("?"); |
| 1486 |
let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub); |
| 1487 |
let mut interval = v["interval"].as_u64().unwrap_or(5).max(1); |
| 1488 |
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900)); |
| 1489 |
eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user)); |
| 1490 |
eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…")); |
| 1491 |
loop { |
| 1492 |
std::thread::sleep(std::time::Duration::from_secs(interval)); |
| 1493 |
if std::time::Instant::now() > deadline { |
| 1494 |
bail!("the code expired before it was approved; run oh auth login again"); |
| 1495 |
} |
| 1496 |
let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?; |
| 1497 |
let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); |
| 1498 |
if code == 200 { |
| 1499 |
return v["access_token"].as_str().map(String::from).context("no token in the hub's answer"); |
| 1500 |
} |
| 1501 |
match v["error"].as_str() { |
| 1502 |
Some("authorization_pending") => {} |
| 1503 |
Some("slow_down") => interval += 5, |
| 1504 |
Some("access_denied") => bail!("the sign-in was denied on the web"), |
| 1505 |
Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"), |
| 1506 |
_ => bail!("signing in: HTTP {code}: {body}"), |
| 1507 |
} |
| 1508 |
} |
| 1509 |
} |
| 1510 |
|
| 1511 |
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> { |
| 1512 |
match (body, file) { |
| 1513 |
(Some(b), _) => Ok(b), |
| 1514 |
(None, Some(f)) if f == "-" => { |
| 1515 |
let mut s = String::new(); |
| 1516 |
std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; |
| 1517 |
Ok(s) |
| 1518 |
} |
| 1519 |
(None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")), |
| 1520 |
(None, None) => Ok(String::new()), |
| 1521 |
} |
| 1522 |
} |
| 1523 |
|
| 1524 |
fn issue_line(i: &Issue) -> String { |
| 1525 |
let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") }; |
| 1526 |
let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect(); |
| 1527 |
format!( |
| 1528 |
"{glyph} {} {}{}{}", |
| 1529 |
ui::dim(&format!("#{}", i.number)), |
| 1530 |
i.title, |
| 1531 |
if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) }, |
| 1532 |
ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms))) |
| 1533 |
) |
| 1534 |
} |
| 1535 |
|
| 1536 |
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> { |
| 1537 |
let base = t.repo_path()?; |
| 1538 |
match cmd { |
| 1539 |
IssueCmd::List { state } => { |
| 1540 |
let path = format!("{base}/issues?state={}", enc(&state)); |
| 1541 |
if json { |
| 1542 |
println!("{}", c.get_text(&path)?); |
| 1543 |
return Ok(0); |
| 1544 |
} |
| 1545 |
let list: Vec<Issue> = c.get(&path)?; |
| 1546 |
if list.is_empty() { |
| 1547 |
println!("{}", ui::dim(&format!("No {state} issues."))); |
| 1548 |
} |
| 1549 |
for i in &list { |
| 1550 |
println!("{}", issue_line(i)); |
| 1551 |
} |
| 1552 |
} |
| 1553 |
IssueCmd::View { number } => { |
| 1554 |
let path = format!("{base}/issues/{number}"); |
| 1555 |
if json { |
| 1556 |
println!("{}", c.get_text(&path)?); |
| 1557 |
return Ok(0); |
| 1558 |
} |
| 1559 |
let i: Issue = c.get(&path)?; |
| 1560 |
println!("{}", issue_line(&i)); |
| 1561 |
if !i.body.trim().is_empty() { |
| 1562 |
println!("\n{}\n", i.body.trim_end()); |
| 1563 |
} |
| 1564 |
let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?; |
| 1565 |
for cm in comments { |
| 1566 |
println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end()); |
| 1567 |
} |
| 1568 |
println!("{}", ui::dim(&i.url)); |
| 1569 |
} |
| 1570 |
IssueCmd::Create { title, body, body_file, label, project, column, attach } => { |
| 1571 |
let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?; |
| 1572 |
let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None }; |
| 1573 |
let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?; |
| 1574 |
if json { |
| 1575 |
println!("{}", serde_json::to_string(&i)?); |
| 1576 |
} else { |
| 1577 |
println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); |
| 1578 |
} |
| 1579 |
if let Some(n) = project { |
| 1580 |
let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() }; |
| 1581 |
let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?; |
| 1582 |
if !json { |
| 1583 |
println!("{} on project {n} as card {}", ui::ok("✔"), added.id); |
| 1584 |
} |
| 1585 |
} |
| 1586 |
} |
| 1587 |
IssueCmd::Close { number, reason, comment } => { |
| 1588 |
comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?; |
| 1589 |
let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?; |
| 1590 |
println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title); |
| 1591 |
} |
| 1592 |
IssueCmd::Reopen { number, comment } => { |
| 1593 |
comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?; |
| 1594 |
let i: Issue = |
| 1595 |
c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?; |
| 1596 |
println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title); |
| 1597 |
} |
| 1598 |
IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => { |
| 1599 |
let body = match (&body, &body_file) { |
| 1600 |
(None, None) => None, |
| 1601 |
_ => Some(body_of(body, body_file)?), |
| 1602 |
}; |
| 1603 |
let labels = if no_labels { |
| 1604 |
Some(Vec::new()) |
| 1605 |
} else if label.is_empty() { |
| 1606 |
None |
| 1607 |
} else { |
| 1608 |
Some(label) |
| 1609 |
}; |
| 1610 |
let assignees = if no_assignees { |
| 1611 |
Some(Vec::new()) |
| 1612 |
} else if assignee.is_empty() { |
| 1613 |
None |
| 1614 |
} else { |
| 1615 |
Some(assignee) |
| 1616 |
}; |
| 1617 |
if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() { |
| 1618 |
bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone"); |
| 1619 |
} |
| 1620 |
let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone }; |
| 1621 |
let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?; |
| 1622 |
if json { |
| 1623 |
println!("{}", serde_json::to_string(&i)?); |
| 1624 |
} else { |
| 1625 |
println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); |
| 1626 |
} |
| 1627 |
} |
| 1628 |
IssueCmd::Label(change) => { |
| 1629 |
let path = format!("{base}/issues/{}", change.number); |
| 1630 |
let now: Issue = c.get(&path)?; |
| 1631 |
let labels = change.apply(&now.labels)?; |
| 1632 |
let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None }; |
| 1633 |
let i: Issue = c.send("PATCH", &path, &edit)?; |
| 1634 |
if json { |
| 1635 |
println!("{}", serde_json::to_string(&i)?); |
| 1636 |
} else { |
| 1637 |
println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels)); |
| 1638 |
} |
| 1639 |
} |
| 1640 |
IssueCmd::Comment { number, body, body_file, attach } => { |
| 1641 |
let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?; |
| 1642 |
if body.trim().is_empty() { |
| 1643 |
bail!("give the comment with --body, --body-file or --attach"); |
| 1644 |
} |
| 1645 |
c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1646 |
println!("{} commented on #{number}", ui::ok("✔")); |
| 1647 |
} |
| 1648 |
} |
| 1649 |
Ok(0) |
| 1650 |
} |
| 1651 |
|
| 1652 |
|
| 1653 |
|
| 1654 |
#[derive(clap::Args)] |
| 1655 |
struct StateComment { |
| 1656 |
|
| 1657 |
#[arg(long, short)] |
| 1658 |
body: Option<String>, |
| 1659 |
|
| 1660 |
#[arg(long, short = 'F', conflicts_with = "body")] |
| 1661 |
body_file: Option<String>, |
| 1662 |
|
| 1663 |
#[arg(long, short = 'a', value_name = "FILE")] |
| 1664 |
attach: Vec<std::path::PathBuf>, |
| 1665 |
} |
| 1666 |
|
| 1667 |
impl StateComment { |
| 1668 |
fn post(self, c: &Client, base: &str, path: &str) -> Result<()> { |
| 1669 |
if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() { |
| 1670 |
return Ok(()); |
| 1671 |
} |
| 1672 |
let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?; |
| 1673 |
if !body.trim().is_empty() { |
| 1674 |
c.send_text("POST", path, &NewComment { body, path: None, line: None })?; |
| 1675 |
} |
| 1676 |
Ok(()) |
| 1677 |
} |
| 1678 |
} |
| 1679 |
|
| 1680 |
|
| 1681 |
|
| 1682 |
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> { |
| 1683 |
if let Some(n) = number { |
| 1684 |
return Ok(n); |
| 1685 |
} |
| 1686 |
let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?; |
| 1687 |
runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark { |
| 1688 |
Some(b) => format!("no runs of {b} among the latest 100"), |
| 1689 |
None => "no runs yet".to_string(), |
| 1690 |
}) |
| 1691 |
} |
| 1692 |
|
| 1693 |
|
| 1694 |
|
| 1695 |
|
| 1696 |
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> { |
| 1697 |
if files.is_empty() { |
| 1698 |
return Ok(body); |
| 1699 |
} |
| 1700 |
let mut links = Vec::new(); |
| 1701 |
for f in files { |
| 1702 |
let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?; |
| 1703 |
let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into()); |
| 1704 |
let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?; |
| 1705 |
let a: hub_api::Attachment = |
| 1706 |
serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?; |
| 1707 |
links.push(a.markdown); |
| 1708 |
} |
| 1709 |
let links = links.join("\n\n"); |
| 1710 |
Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) }) |
| 1711 |
} |
| 1712 |
|
| 1713 |
fn source_name(s: &hub_api::ProposalSource) -> String { |
| 1714 |
match s { |
| 1715 |
hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(), |
| 1716 |
hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"), |
| 1717 |
hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()), |
| 1718 |
} |
| 1719 |
} |
| 1720 |
|
| 1721 |
fn proposal_line(p: &Proposal) -> String { |
| 1722 |
let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default(); |
| 1723 |
let glyph = match state.as_str() { |
| 1724 |
"open" => ui::ok("●"), |
| 1725 |
"draft" => ui::dim("◌"), |
| 1726 |
"landed" => ui::strong("✔"), |
| 1727 |
_ => ui::dim("○"), |
| 1728 |
}; |
| 1729 |
format!( |
| 1730 |
"{glyph} {} {} {}{}", |
| 1731 |
ui::dim(&format!("#{}", p.number)), |
| 1732 |
p.title, |
| 1733 |
ui::dim(&format!("{} → {}", source_name(&p.source), p.target)), |
| 1734 |
ui::dim(&format!(" · {} · {state}", p.author)) |
| 1735 |
) |
| 1736 |
} |
| 1737 |
|
| 1738 |
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> { |
| 1739 |
let base = t.repo_path()?; |
| 1740 |
match cmd { |
| 1741 |
ProposalCmd::List { state, limit } => { |
| 1742 |
let path = format!("{base}/proposals?state={state}&limit={limit}"); |
| 1743 |
if json { |
| 1744 |
println!("{}", c.get_text(&path)?); |
| 1745 |
return Ok(0); |
| 1746 |
} |
| 1747 |
let list: Vec<Proposal> = c.get(&path)?; |
| 1748 |
if list.is_empty() { |
| 1749 |
println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace(" ", " "))); |
| 1750 |
} |
| 1751 |
for p in &list { |
| 1752 |
println!("{}", proposal_line(p)); |
| 1753 |
} |
| 1754 |
} |
| 1755 |
ProposalCmd::View { number } => { |
| 1756 |
let path = format!("{base}/proposals/{number}"); |
| 1757 |
if json { |
| 1758 |
println!("{}", c.get_text(&path)?); |
| 1759 |
return Ok(0); |
| 1760 |
} |
| 1761 |
let p: Proposal = c.get(&path)?; |
| 1762 |
println!("{}", proposal_line(&p)); |
| 1763 |
if !p.body.trim().is_empty() { |
| 1764 |
println!("\n{}\n", p.body.trim_end()); |
| 1765 |
} |
| 1766 |
println!("{}", ui::kv("changes", &p.changes.len().to_string())); |
| 1767 |
for ch in &p.changes { |
| 1768 |
println!(" {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or("")); |
| 1769 |
} |
| 1770 |
println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", "))); |
| 1771 |
if p.landable { |
| 1772 |
println!("{} can land", ui::ok("✔")); |
| 1773 |
} else { |
| 1774 |
for b in &p.blockers { |
| 1775 |
println!("{} {b}", ui::bad("✘")); |
| 1776 |
} |
| 1777 |
} |
| 1778 |
if p.conflicted { |
| 1779 |
println!("{} landing it would leave conflicts", ui::bad("!")); |
| 1780 |
} |
| 1781 |
println!("{}", ui::dim(&p.url)); |
| 1782 |
} |
| 1783 |
ProposalCmd::Create { title, body, body_file, from, into, draft } => { |
| 1784 |
let target = match into { |
| 1785 |
Some(i) => i, |
| 1786 |
None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(), |
| 1787 |
}; |
| 1788 |
let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft }; |
| 1789 |
let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?; |
| 1790 |
if json { |
| 1791 |
println!("{}", serde_json::to_string(&p)?); |
| 1792 |
} else { |
| 1793 |
println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); |
| 1794 |
} |
| 1795 |
} |
| 1796 |
ProposalCmd::Edit { number, title, body, body_file } => { |
| 1797 |
let body = match (&body, &body_file) { |
| 1798 |
(None, None) => None, |
| 1799 |
_ => Some(body_of(body, body_file)?), |
| 1800 |
}; |
| 1801 |
if title.is_none() && body.is_none() { |
| 1802 |
bail!("say what to change: --title, --body or --body-file"); |
| 1803 |
} |
| 1804 |
let edit = hub_api::ProposalEdit { title, body, ..Default::default() }; |
| 1805 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; |
| 1806 |
if json { |
| 1807 |
println!("{}", serde_json::to_string(&p)?); |
| 1808 |
} else { |
| 1809 |
println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); |
| 1810 |
} |
| 1811 |
} |
| 1812 |
ProposalCmd::Label(change) => { |
| 1813 |
let path = format!("{base}/proposals/{}", change.number); |
| 1814 |
let now: Proposal = c.get(&path)?; |
| 1815 |
let labels = change.apply(&now.labels)?; |
| 1816 |
let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() }; |
| 1817 |
let p: Proposal = c.send("PATCH", &path, &edit)?; |
| 1818 |
if json { |
| 1819 |
println!("{}", serde_json::to_string(&p)?); |
| 1820 |
} else { |
| 1821 |
println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels)); |
| 1822 |
} |
| 1823 |
} |
| 1824 |
ProposalCmd::Comment { number, body, body_file } => { |
| 1825 |
let body = body_of(body, body_file)?; |
| 1826 |
if body.trim().is_empty() { |
| 1827 |
bail!("give the comment with --body or --body-file"); |
| 1828 |
} |
| 1829 |
c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1830 |
println!("{} commented on #{number}", ui::ok("✔")); |
| 1831 |
} |
| 1832 |
ProposalCmd::Land { number, when_ready: true, off, .. } => { |
| 1833 |
let path = format!("{base}/proposals/{number}/auto-land"); |
| 1834 |
let p: Proposal = |
| 1835 |
if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? }; |
| 1836 |
if json { |
| 1837 |
println!("{}", serde_json::to_string(&p)?); |
| 1838 |
} else if p.landed.is_some() { |
| 1839 |
println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target); |
| 1840 |
} else if p.auto_land.is_some() { |
| 1841 |
println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number); |
| 1842 |
} else { |
| 1843 |
println!("{} #{} will not land by itself", ui::ok("✔"), p.number); |
| 1844 |
} |
| 1845 |
} |
| 1846 |
ProposalCmd::Land { number, over_checks, .. } => { |
| 1847 |
let body = match &over_checks { |
| 1848 |
Some(r) => serde_json::json!({ "over_checks": r }), |
| 1849 |
None => serde_json::json!({}), |
| 1850 |
}; |
| 1851 |
let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?; |
| 1852 |
if json { |
| 1853 |
println!("{}", serde_json::to_string(&p)?); |
| 1854 |
} else { |
| 1855 |
println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target); |
| 1856 |
} |
| 1857 |
} |
| 1858 |
ProposalCmd::Close { number, message } => { |
| 1859 |
if let Some(body) = message { |
| 1860 |
c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; |
| 1861 |
} |
| 1862 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?; |
| 1863 |
if json { |
| 1864 |
println!("{}", serde_json::to_string(&p)?); |
| 1865 |
} else { |
| 1866 |
println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title); |
| 1867 |
} |
| 1868 |
} |
| 1869 |
ProposalCmd::Reopen { number } => { |
| 1870 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?; |
| 1871 |
if json { |
| 1872 |
println!("{}", serde_json::to_string(&p)?); |
| 1873 |
} else { |
| 1874 |
println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title); |
| 1875 |
} |
| 1876 |
} |
| 1877 |
ProposalCmd::Ready { number, undo } => { |
| 1878 |
let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() }; |
| 1879 |
let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; |
| 1880 |
if json { |
| 1881 |
println!("{}", serde_json::to_string(&p)?); |
| 1882 |
} else if undo { |
| 1883 |
println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title); |
| 1884 |
} else { |
| 1885 |
println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title); |
| 1886 |
} |
| 1887 |
} |
| 1888 |
ProposalCmd::Checks { number } => { |
| 1889 |
let path = format!("{base}/proposals/{number}/checks"); |
| 1890 |
if json { |
| 1891 |
println!("{}", c.get_text(&path)?); |
| 1892 |
return Ok(0); |
| 1893 |
} |
| 1894 |
let checks: Vec<hub_api::Check> = c.get(&path)?; |
| 1895 |
if checks.is_empty() { |
| 1896 |
println!("{}", ui::dim("No checks yet.")); |
| 1897 |
} |
| 1898 |
for ch in checks { |
| 1899 |
println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary)); |
| 1900 |
} |
| 1901 |
} |
| 1902 |
} |
| 1903 |
Ok(0) |
| 1904 |
} |
| 1905 |
|
| 1906 |
fn run_line(r: &FlowRun) -> String { |
| 1907 |
let what = |
| 1908 |
if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() }; |
| 1909 |
format!( |
| 1910 |
"{} {} {} {}", |
| 1911 |
ui::status(&r.status), |
| 1912 |
ui::dim(&format!("#{}", r.number)), |
| 1913 |
what, |
| 1914 |
ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms))) |
| 1915 |
) |
| 1916 |
} |
| 1917 |
|
| 1918 |
fn print_run(r: &FlowRun, timings: bool) { |
| 1919 |
println!("{}", run_line(r)); |
| 1920 |
for j in &r.jobs { |
| 1921 |
let dur = match (j.started_ms, j.finished_ms) { |
| 1922 |
(Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0), |
| 1923 |
_ => String::new(), |
| 1924 |
}; |
| 1925 |
let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) }; |
| 1926 |
println!(" {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}"))); |
| 1927 |
|
| 1928 |
|
| 1929 |
if j.status == "queued" && !j.waiting.is_empty() { |
| 1930 |
println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); |
| 1931 |
} else if !j.placed.is_empty() { |
| 1932 |
println!(" {}", ui::dim(&format!("placed: {}", j.placed))); |
| 1933 |
} |
| 1934 |
if timings { |
| 1935 |
let t = timing_line(j); |
| 1936 |
if !t.is_empty() { |
| 1937 |
println!(" {}", ui::dim(&t)); |
| 1938 |
} |
| 1939 |
} |
| 1940 |
} |
| 1941 |
if !r.error.is_empty() { |
| 1942 |
println!("{}", ui::bad(&r.error)); |
| 1943 |
} |
| 1944 |
println!("{}", ui::dim(&r.url)); |
| 1945 |
} |
| 1946 |
|
| 1947 |
|
| 1948 |
fn took(ms: i64) -> String { |
| 1949 |
match ms { |
| 1950 |
..=999 => format!("{ms} ms"), |
| 1951 |
1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0), |
| 1952 |
_ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000), |
| 1953 |
} |
| 1954 |
} |
| 1955 |
|
| 1956 |
|
| 1957 |
fn mib(m: i64) -> String { |
| 1958 |
if m >= 1024 { |
| 1959 |
format!("{:.1} GiB", m as f64 / 1024.0) |
| 1960 |
} else { |
| 1961 |
format!("{m} MiB") |
| 1962 |
} |
| 1963 |
} |
| 1964 |
|
| 1965 |
|
| 1966 |
|
| 1967 |
fn timing_line(j: &FlowJob) -> String { |
| 1968 |
let mut parts = vec![]; |
| 1969 |
if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) { |
| 1970 |
parts.push(format!("waited {}", took((s - q).max(0)))); |
| 1971 |
} |
| 1972 |
parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64)))); |
| 1973 |
let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)] |
| 1974 |
.into_iter() |
| 1975 |
.filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m)))) |
| 1976 |
.collect(); |
| 1977 |
if !peaks.is_empty() { |
| 1978 |
parts.push(format!("peak {}", peaks.join(", "))); |
| 1979 |
} |
| 1980 |
parts.join(" · ") |
| 1981 |
} |
| 1982 |
|
| 1983 |
|
| 1984 |
fn enc_path(path: &str) -> String { |
| 1985 |
path.split('/').map(enc).collect::<Vec<_>>().join("/") |
| 1986 |
} |
| 1987 |
|
| 1988 |
|
| 1989 |
|
| 1990 |
|
| 1991 |
fn show_report( |
| 1992 |
c: &Client, |
| 1993 |
at: &str, |
| 1994 |
files: impl Fn(&str) -> String, |
| 1995 |
list: bool, |
| 1996 |
file: Option<String>, |
| 1997 |
output: Option<std::path::PathBuf>, |
| 1998 |
json: bool, |
| 1999 |
) -> Result<()> { |
| 2000 |
use std::io::Write; |
| 2001 |
if let Some(path) = file { |
| 2002 |
let bytes = c.get_bytes(&files(&path))?; |
| 2003 |
match output { |
| 2004 |
Some(out) => { |
| 2005 |
std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?; |
| 2006 |
eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display()); |
| 2007 |
} |
| 2008 |
None => std::io::stdout().write_all(&bytes)?, |
| 2009 |
} |
| 2010 |
return Ok(()); |
| 2011 |
} |
| 2012 |
if json { |
| 2013 |
println!("{}", c.get_text(at)?); |
| 2014 |
return Ok(()); |
| 2015 |
} |
| 2016 |
if !list { |
| 2017 |
std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?; |
| 2018 |
return Ok(()); |
| 2019 |
} |
| 2020 |
let r: Report = c.get(at)?; |
| 2021 |
print_report(&r); |
| 2022 |
if r.files_expired_ms.is_some() { |
| 2023 |
println!("{}", ui::warn("its files expired under retention; its metrics stay")); |
| 2024 |
} |
| 2025 |
for f in &r.manifest { |
| 2026 |
println!(" {:>10} {}", ui::dim(&f.size.to_string()), f.path); |
| 2027 |
} |
| 2028 |
println!("{}", ui::dim(&r.url)); |
| 2029 |
Ok(()) |
| 2030 |
} |
| 2031 |
|
| 2032 |
|
| 2033 |
fn print_report(r: &Report) { |
| 2034 |
let from = match r.run { |
| 2035 |
Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark), |
| 2036 |
None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }), |
| 2037 |
}; |
| 2038 |
println!( |
| 2039 |
"{} {} {}", |
| 2040 |
ui::strong(&r.name), |
| 2041 |
ui::dim(&format!("{} · {:?}", r.kind, r.title)), |
| 2042 |
ui::dim(&format!("· {from} · {} files", r.files)) |
| 2043 |
); |
| 2044 |
if !r.summary.is_empty() { |
| 2045 |
println!(" {}", r.summary); |
| 2046 |
} |
| 2047 |
for m in &r.metrics { |
| 2048 |
let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) }; |
| 2049 |
let mut notes = vec![]; |
| 2050 |
if !m.better.is_empty() { |
| 2051 |
notes.push(format!("{} is better", m.better)); |
| 2052 |
} |
| 2053 |
if let Some(a) = m.fail_above { |
| 2054 |
notes.push(format!("fails above {a}")); |
| 2055 |
} |
| 2056 |
if let Some(b) = m.fail_below { |
| 2057 |
notes.push(format!("fails below {b}")); |
| 2058 |
} |
| 2059 |
let notes = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join(", ")) }; |
| 2060 |
println!(" {} {}{unit}{}", m.key, m.value, ui::dim(¬es)); |
| 2061 |
} |
| 2062 |
if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) { |
| 2063 |
let line: Vec<String> = |
| 2064 |
ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect(); |
| 2065 |
println!(" {}", ui::dim(&line.join(" "))); |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
|
| 2070 |
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> { |
| 2071 |
let base = t.repo_path()?; |
| 2072 |
match cmd { |
| 2073 |
ReportCmd::List { bookmark } => { |
| 2074 |
let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default()); |
| 2075 |
if json { |
| 2076 |
println!("{}", c.get_text(&path)?); |
| 2077 |
return Ok(0); |
| 2078 |
} |
| 2079 |
let list: Vec<Report> = c.get(&path)?; |
| 2080 |
if list.is_empty() { |
| 2081 |
println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`.")); |
| 2082 |
} |
| 2083 |
for r in &list { |
| 2084 |
print_report(r); |
| 2085 |
} |
| 2086 |
} |
| 2087 |
ReportCmd::Show { report, id, bookmark, list, file, output } => { |
| 2088 |
let at = format!("{base}/reports/{}", enc(&report)); |
| 2089 |
let query = match (id, bookmark) { |
| 2090 |
(Some(id), _) => format!("?id={id}"), |
| 2091 |
(None, Some(b)) => format!("?bookmark={}", enc(&b)), |
| 2092 |
(None, None) => String::new(), |
| 2093 |
}; |
| 2094 |
let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path)); |
| 2095 |
show_report(c, &format!("{at}{query}"), files, list, file, output, json)?; |
| 2096 |
} |
| 2097 |
} |
| 2098 |
Ok(0) |
| 2099 |
} |
| 2100 |
|
| 2101 |
fn live(status: &str) -> bool { |
| 2102 |
matches!(status, "queued" | "running") |
| 2103 |
} |
| 2104 |
|
| 2105 |
|
| 2106 |
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> { |
| 2107 |
let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?; |
| 2108 |
if json { |
| 2109 |
println!("{done}"); |
| 2110 |
} else { |
| 2111 |
println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or("")); |
| 2112 |
} |
| 2113 |
Ok(()) |
| 2114 |
} |
| 2115 |
|
| 2116 |
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> { |
| 2117 |
let path = format!("{base}/flow/runs/{number}"); |
| 2118 |
let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new(); |
| 2119 |
loop { |
| 2120 |
let r: FlowRun = c.get(&path)?; |
| 2121 |
if !json { |
| 2122 |
for j in &r.jobs { |
| 2123 |
let shown = format!("{}\u{0}{}", j.status, j.waiting); |
| 2124 |
if seen.get(&j.name) != Some(&shown) { |
| 2125 |
println!("{} {}", ui::status(&j.status), j.name); |
| 2126 |
if j.status == "queued" && !j.waiting.is_empty() { |
| 2127 |
println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); |
| 2128 |
} |
| 2129 |
seen.insert(j.name.clone(), shown); |
| 2130 |
} |
| 2131 |
} |
| 2132 |
} |
| 2133 |
if !live(&r.status) { |
| 2134 |
if json { |
| 2135 |
println!("{}", serde_json::to_string(&r)?); |
| 2136 |
} else { |
| 2137 |
println!("{} run #{} {}", ui::status(&r.status), r.number, r.status); |
| 2138 |
} |
| 2139 |
return Ok(if r.status == "passed" { 0 } else { 1 }); |
| 2140 |
} |
| 2141 |
std::thread::sleep(Duration::from_secs(3)); |
| 2142 |
} |
| 2143 |
} |
| 2144 |
|
| 2145 |
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> { |
| 2146 |
let base = t.repo_path()?; |
| 2147 |
match cmd { |
| 2148 |
RunCmd::List { limit } => { |
| 2149 |
let path = format!("{base}/flow/runs?limit={limit}"); |
| 2150 |
if json { |
| 2151 |
println!("{}", c.get_text(&path)?); |
| 2152 |
return Ok(0); |
| 2153 |
} |
| 2154 |
let runs: Vec<FlowRun> = c.get(&path)?; |
| 2155 |
if runs.is_empty() { |
| 2156 |
println!("{}", ui::dim("No runs yet.")); |
| 2157 |
} |
| 2158 |
for r in &runs { |
| 2159 |
println!("{}", run_line(r)); |
| 2160 |
} |
| 2161 |
} |
| 2162 |
RunCmd::View { number, bookmark, timings } => { |
| 2163 |
let number = run_or_newest(c, &base, number, bookmark.as_deref())?; |
| 2164 |
let path = format!("{base}/flow/runs/{number}"); |
| 2165 |
if json { |
| 2166 |
println!("{}", c.get_text(&path)?); |
| 2167 |
return Ok(0); |
| 2168 |
} |
| 2169 |
print_run(&c.get(&path)?, timings); |
| 2170 |
} |
| 2171 |
RunCmd::Start { bookmark, change, jobs, watch: follow } => { |
| 2172 |
let mut body = match (bookmark, change) { |
| 2173 |
(_, Some(ch)) => serde_json::json!({ "change": ch }), |
| 2174 |
(Some(b), None) => serde_json::json!({ "bookmark": b }), |
| 2175 |
(None, None) => serde_json::json!({}), |
| 2176 |
}; |
| 2177 |
if !jobs.is_empty() { |
| 2178 |
body["jobs"] = serde_json::json!(jobs); |
| 2179 |
} |
| 2180 |
let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?; |
| 2181 |
let n = started["number"].as_i64().context("the hub named no run")?; |
| 2182 |
if !json || !follow { |
| 2183 |
if json { |
| 2184 |
println!("{started}"); |
| 2185 |
} else { |
| 2186 |
println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or(""))); |
| 2187 |
} |
| 2188 |
} |
| 2189 |
if follow { |
| 2190 |
return watch(c, &base, n, json); |
| 2191 |
} |
| 2192 |
} |
| 2193 |
RunCmd::Watch { number, bookmark } => { |
| 2194 |
let number = run_or_newest(c, &base, number, bookmark.as_deref())?; |
| 2195 |
return watch(c, &base, number, json); |
| 2196 |
} |
| 2197 |
RunCmd::Log { number, job } => { |
| 2198 |
let mut after = 0; |
| 2199 |
loop { |
| 2200 |
let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job)); |
| 2201 |
let lines: Vec<FlowLogLine> = c.get(&path)?; |
| 2202 |
if lines.is_empty() { |
| 2203 |
break; |
| 2204 |
} |
| 2205 |
for l in &lines { |
| 2206 |
if json { |
| 2207 |
println!("{}", serde_json::to_string(l)?); |
| 2208 |
} else if l.stream == "flow" { |
| 2209 |
println!("{}", ui::dim(&l.text)); |
| 2210 |
} else { |
| 2211 |
println!("{}", l.text); |
| 2212 |
} |
| 2213 |
} |
| 2214 |
after = lines.last().map(|l| l.seq).unwrap_or(after); |
| 2215 |
} |
| 2216 |
} |
| 2217 |
RunCmd::Report { number, job, pick } => { |
| 2218 |
let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job)); |
| 2219 |
let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default(); |
| 2220 |
let files = |path: &str| format!("{at}/{}{query}", enc_path(path)); |
| 2221 |
show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?; |
| 2222 |
} |
| 2223 |
RunCmd::Rerun { number, job: Some(job) } => { |
| 2224 |
let queued: serde_json::Value = |
| 2225 |
c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?; |
| 2226 |
if json { |
| 2227 |
println!("{queued}"); |
| 2228 |
} else { |
| 2229 |
let n = queued["queued"].as_i64().unwrap_or(1); |
| 2230 |
let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() }; |
| 2231 |
println!("{} queued {job} of run #{number} again{with}", ui::ok("✔")); |
| 2232 |
} |
| 2233 |
} |
| 2234 |
RunCmd::Rerun { number, job: None } => { |
| 2235 |
let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?; |
| 2236 |
if json { |
| 2237 |
println!("{started}"); |
| 2238 |
} else { |
| 2239 |
println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or(""))); |
| 2240 |
} |
| 2241 |
} |
| 2242 |
RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?, |
| 2243 |
RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?, |
| 2244 |
RunCmd::Cancel { number } => { |
| 2245 |
let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?; |
| 2246 |
if json { |
| 2247 |
println!("{done}"); |
| 2248 |
} else { |
| 2249 |
println!("{} cancelled run #{number}", ui::ok("✔")); |
| 2250 |
} |
| 2251 |
} |
| 2252 |
} |
| 2253 |
Ok(0) |
| 2254 |
} |
| 2255 |
|
| 2256 |
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> { |
| 2257 |
let base = t.repo_path()?; |
| 2258 |
match cmd { |
| 2259 |
LabelCmd::List => { |
| 2260 |
let path = format!("{base}/labels"); |
| 2261 |
if json { |
| 2262 |
println!("{}", c.get_text(&path)?); |
| 2263 |
return Ok(0); |
| 2264 |
} |
| 2265 |
let labels: Vec<hub_api::Label> = c.get(&path)?; |
| 2266 |
if labels.is_empty() { |
| 2267 |
println!("{}", ui::dim("No labels.")); |
| 2268 |
} |
| 2269 |
for l in labels { |
| 2270 |
println!("{} {} {}", ui::dim(&l.colour), l.name, ui::dim(&l.description)); |
| 2271 |
} |
| 2272 |
} |
| 2273 |
LabelCmd::Create { name, colour, description } => { |
| 2274 |
let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?; |
| 2275 |
if json { |
| 2276 |
println!("{}", serde_json::to_string(&l)?); |
| 2277 |
} else { |
| 2278 |
println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour)); |
| 2279 |
} |
| 2280 |
} |
| 2281 |
LabelCmd::Delete { name } => { |
| 2282 |
c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?; |
| 2283 |
println!("{} deleted label {name}", ui::ok("✔")); |
| 2284 |
} |
| 2285 |
} |
| 2286 |
Ok(0) |
| 2287 |
} |
| 2288 |
|
| 2289 |
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> { |
| 2290 |
let base = match (&org, site) { |
| 2291 |
(Some(o), _) => format!("/orgs/{}/assistants", enc(o)), |
| 2292 |
(None, true) => "/admin/assistants".to_string(), |
| 2293 |
(None, false) => format!("{}/assistants", t.repo_path()?), |
| 2294 |
}; |
| 2295 |
match cmd { |
| 2296 |
AssistantCmd::List => { |
| 2297 |
if json { |
| 2298 |
println!("{}", c.get_text(&base)?); |
| 2299 |
return Ok(0); |
| 2300 |
} |
| 2301 |
let list: Vec<hub_api::Assistant> = c.get(&base)?; |
| 2302 |
if list.is_empty() { |
| 2303 |
println!("{}", ui::dim("No assistants.")); |
| 2304 |
} |
| 2305 |
for a in list { |
| 2306 |
let state = if a.enabled && !a.off_above { |
| 2307 |
ui::ok("on") |
| 2308 |
} else if a.off_above { |
| 2309 |
ui::dim("off above") |
| 2310 |
} else { |
| 2311 |
ui::dim("off") |
| 2312 |
}; |
| 2313 |
let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) }; |
| 2314 |
println!("{} {} {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from); |
| 2315 |
} |
| 2316 |
} |
| 2317 |
AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => { |
| 2318 |
let token = match token_env { |
| 2319 |
Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?, |
| 2320 |
None => String::new(), |
| 2321 |
}; |
| 2322 |
let body = |
| 2323 |
hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None }; |
| 2324 |
let r: serde_json::Value = c.send("POST", &base, &body)?; |
| 2325 |
println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved")); |
| 2326 |
} |
| 2327 |
AssistantCmd::Remove { name } => { |
| 2328 |
c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?; |
| 2329 |
println!("{} removed {name}", ui::ok("✔")); |
| 2330 |
} |
| 2331 |
AssistantCmd::Prompt { set } => { |
| 2332 |
let p: hub_api::AssistantPrompt = match set { |
| 2333 |
Some(path) => { |
| 2334 |
let text = if path.as_os_str() == "-" { |
| 2335 |
let mut s = String::new(); |
| 2336 |
std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; |
| 2337 |
s |
| 2338 |
} else { |
| 2339 |
std::fs::read_to_string(&path)? |
| 2340 |
}; |
| 2341 |
c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })? |
| 2342 |
} |
| 2343 |
None => c.get(&format!("{base}/prompt"))?, |
| 2344 |
}; |
| 2345 |
if json { |
| 2346 |
println!("{}", serde_json::to_string(&p)?); |
| 2347 |
return Ok(0); |
| 2348 |
} |
| 2349 |
for (from, text) in &p.inherited { |
| 2350 |
println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text); |
| 2351 |
} |
| 2352 |
if p.prompt.is_empty() { |
| 2353 |
println!("{}", ui::dim("No prompt of its own.")); |
| 2354 |
} else { |
| 2355 |
println!("{}\n{}", ui::dim("── this level"), p.prompt); |
| 2356 |
} |
| 2357 |
} |
| 2358 |
} |
| 2359 |
Ok(0) |
| 2360 |
} |
| 2361 |
|
| 2362 |
fn project_line(p: &hub_api::Project) -> String { |
| 2363 |
let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") }; |
| 2364 |
let private = if p.public { "" } else { " · private" }; |
| 2365 |
format!("{glyph} {} {} {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms)))) |
| 2366 |
} |
| 2367 |
|
| 2368 |
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> { |
| 2369 |
let owner = match owner { |
| 2370 |
Some(o) => o, |
| 2371 |
None => t.repo()?.0.to_string(), |
| 2372 |
}; |
| 2373 |
let base = format!("/projects/{}", enc(&owner)); |
| 2374 |
let state = |number: i64, closed: bool, verb: &str| -> Result<()> { |
| 2375 |
let p: hub_api::Project = |
| 2376 |
c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?; |
| 2377 |
if json { |
| 2378 |
println!("{}", serde_json::to_string(&p)?); |
| 2379 |
} else { |
| 2380 |
println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title); |
| 2381 |
} |
| 2382 |
Ok(()) |
| 2383 |
}; |
| 2384 |
match cmd { |
| 2385 |
ProjectCmd::List => { |
| 2386 |
if json { |
| 2387 |
println!("{}", c.get_text(&base)?); |
| 2388 |
return Ok(0); |
| 2389 |
} |
| 2390 |
let list: Vec<hub_api::Project> = c.get(&base)?; |
| 2391 |
if list.is_empty() { |
| 2392 |
println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE"))); |
| 2393 |
} |
| 2394 |
for p in &list { |
| 2395 |
println!("{}", project_line(p)); |
| 2396 |
} |
| 2397 |
} |
| 2398 |
ProjectCmd::View { number, archived, filter, view } => { |
| 2399 |
let cards = format!("{base}/{number}/cards?archived=true"); |
| 2400 |
let path = match (&filter, &view) { |
| 2401 |
(Some(q), _) => format!("{base}/{number}?q={}", enc(q)), |
| 2402 |
(None, Some(v)) => format!("{base}/{number}?view={}", enc(v)), |
| 2403 |
(None, None) => format!("{base}/{number}"), |
| 2404 |
}; |
| 2405 |
if json { |
| 2406 |
println!("{}", c.get_text(if archived { &cards } else { &path })?); |
| 2407 |
return Ok(0); |
| 2408 |
} |
| 2409 |
let mut b: hub_api::Board = c.get(&path)?; |
| 2410 |
if archived { |
| 2411 |
b.columns = c.get(&cards)?; |
| 2412 |
} |
| 2413 |
println!("{}", project_line(&b.project)); |
| 2414 |
if !b.project.description.is_empty() { |
| 2415 |
println!("{}", b.project.description); |
| 2416 |
} |
| 2417 |
if !b.filter.is_empty() { |
| 2418 |
println!("{}", ui::dim(&format!("filter: {}", b.filter))); |
| 2419 |
} |
| 2420 |
if !b.views.is_empty() && filter.is_none() && view.is_none() { |
| 2421 |
let names: Vec<&str> = b.views.iter().map(|v| v.name.as_str()).collect(); |
| 2422 |
println!("{}", ui::dim(&format!("views: {} (oh project view {number} --view NAME)", names.join(", ")))); |
| 2423 |
} |
| 2424 |
for col in &b.columns { |
| 2425 |
println!(); |
| 2426 |
let wip = match col.wip_limit { |
| 2427 |
Some(w) if col.cards.len() as i64 > w => format!(" · over its limit of {w}"), |
| 2428 |
Some(w) => format!(" · limit {w}"), |
| 2429 |
None => String::new(), |
| 2430 |
}; |
| 2431 |
println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}{wip}", col.cards.len(), col.id))); |
| 2432 |
if col.cards.is_empty() { |
| 2433 |
println!(" {}", ui::dim("(empty)")); |
| 2434 |
} |
| 2435 |
for card in &col.cards { |
| 2436 |
let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() }; |
| 2437 |
let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) }; |
| 2438 |
let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect(); |
| 2439 |
tags.extend(card.assignees.iter().map(|a| format!("@{a}"))); |
| 2440 |
let tags = if tags.is_empty() { String::new() } else { format!(" {}", ui::dim(&tags.join(" "))) }; |
| 2441 |
println!(" {} {what}{st} {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title); |
| 2442 |
} |
| 2443 |
} |
| 2444 |
println!("{}", ui::dim(&format!("\n{}", b.project.url))); |
| 2445 |
} |
| 2446 |
ProjectCmd::Create { title, description, private } => { |
| 2447 |
let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?; |
| 2448 |
if json { |
| 2449 |
println!("{}", serde_json::to_string(&p)?); |
| 2450 |
} else { |
| 2451 |
println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url)); |
| 2452 |
} |
| 2453 |
} |
| 2454 |
ProjectCmd::Charts { number, filter } => { |
| 2455 |
let path = match &filter { |
| 2456 |
Some(q) => format!("{base}/{number}/charts?q={}", enc(q)), |
| 2457 |
None => format!("{base}/{number}/charts"), |
| 2458 |
}; |
| 2459 |
if json { |
| 2460 |
println!("{}", c.get_text(&path)?); |
| 2461 |
return Ok(0); |
| 2462 |
} |
| 2463 |
let ch: hub_api::BoardCharts = c.get(&path)?; |
| 2464 |
println!("{}", ui::strong("Forecasts")); |
| 2465 |
for f in &ch.forecasts { |
| 2466 |
let when = match (&f.p50, &f.p85) { |
| 2467 |
(Some(a), Some(b)) => format!("50% by {a}, 85% by {b}"), |
| 2468 |
(Some(a), None) => format!("50% by {a}, 85% beyond ten years"), |
| 2469 |
_ => "no forecast: nothing has reached Done in the weeks it draws from".to_string(), |
| 2470 |
}; |
| 2471 |
println!(" {} {} left · {when}", f.scope, f.remaining); |
| 2472 |
} |
| 2473 |
if let Some(f) = ch.forecasts.first() { |
| 2474 |
println!(" {}", ui::dim(&format!("from {} week(s) of throughput", f.weeks_of_history))); |
| 2475 |
} |
| 2476 |
println!(); |
| 2477 |
match (ch.cycle_time_median_days, ch.cycle_time_p85_days) { |
| 2478 |
(Some(m), Some(p)) => { |
| 2479 |
println!("{} median {m} d, 85th percentile {p} d over {} finished", ui::strong("Cycle time"), ch.finished) |
| 2480 |
} |
| 2481 |
_ => println!("{} {}", ui::strong("Cycle time"), ui::dim("no card has gone from started to Done yet")), |
| 2482 |
} |
| 2483 |
let weeks: Vec<String> = ch.throughput.iter().map(|w| w.done.to_string()).collect(); |
| 2484 |
println!("{} {} {}", ui::strong("Throughput"), weeks.join(" "), ui::dim("(cards done each week, oldest first)")); |
| 2485 |
if let Some(b) = &ch.burn_down { |
| 2486 |
println!( |
| 2487 |
"{} {}: {} left of {}", |
| 2488 |
ui::strong("Burn-down"), |
| 2489 |
b.iteration, |
| 2490 |
b.left.last().unwrap_or(&0), |
| 2491 |
b.scope.last().unwrap_or(&0) |
| 2492 |
); |
| 2493 |
} |
| 2494 |
} |
| 2495 |
ProjectCmd::Column { cmd } => { |
| 2496 |
let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column)); |
| 2497 |
let (number, b, what): (i64, hub_api::Board, String) = match cmd { |
| 2498 |
ColumnCmd::Add { number, name } => { |
| 2499 |
let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?; |
| 2500 |
(number, b, format!("added column {name}")) |
| 2501 |
} |
| 2502 |
ColumnCmd::Rename { number, column, to } => { |
| 2503 |
let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None }; |
| 2504 |
(number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}")) |
| 2505 |
} |
| 2506 |
ColumnCmd::Move { number, column, to, left, right } => { |
| 2507 |
let position = match to { |
| 2508 |
Some(n) => n - 1, |
| 2509 |
None => { |
| 2510 |
let now: hub_api::Board = c.get(&format!("{base}/{number}"))?; |
| 2511 |
let at = now |
| 2512 |
.columns |
| 2513 |
.iter() |
| 2514 |
.position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column)) |
| 2515 |
.with_context(|| format!("no column {column} on board {number}"))? |
| 2516 |
as i64; |
| 2517 |
if left { |
| 2518 |
(at - 1).max(0) |
| 2519 |
} else { |
| 2520 |
debug_assert!(right); |
| 2521 |
at + 1 |
| 2522 |
} |
| 2523 |
} |
| 2524 |
}; |
| 2525 |
let edit = hub_api::ColumnEdit { name: None, position: Some(position) }; |
| 2526 |
(number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}")) |
| 2527 |
} |
| 2528 |
ColumnCmd::Remove { number, column } => { |
| 2529 |
(number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}")) |
| 2530 |
} |
| 2531 |
}; |
| 2532 |
if json { |
| 2533 |
println!("{}", serde_json::to_string(&b)?); |
| 2534 |
} else { |
| 2535 |
let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect(); |
| 2536 |
println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · "))); |
| 2537 |
} |
| 2538 |
} |
| 2539 |
ProjectCmd::Close { number } => state(number, true, "closed")?, |
| 2540 |
ProjectCmd::Reopen { number } => state(number, false, "reopened")?, |
| 2541 |
ProjectCmd::Transfer { number, to } => { |
| 2542 |
let p: hub_api::Project = |
| 2543 |
c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?; |
| 2544 |
if json { |
| 2545 |
println!("{}", serde_json::to_string(&p)?); |
| 2546 |
} else { |
| 2547 |
println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url); |
| 2548 |
} |
| 2549 |
} |
| 2550 |
ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => { |
| 2551 |
|
| 2552 |
|
| 2553 |
let reference = match reference { |
| 2554 |
None => String::new(), |
| 2555 |
Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') { |
| 2556 |
Some((o, rest)) if o == owner => rest.to_string(), |
| 2557 |
Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"), |
| 2558 |
None => r, |
| 2559 |
}, |
| 2560 |
Some(r) => { |
| 2561 |
let n = r.trim_start_matches('#'); |
| 2562 |
if n.parse::<i64>().is_err() { |
| 2563 |
bail!("{r}: give an issue or proposal number, or NAME#N"); |
| 2564 |
} |
| 2565 |
format!("{}#{n}", t.repo()?.1) |
| 2566 |
} |
| 2567 |
}; |
| 2568 |
let note = note.unwrap_or_default(); |
| 2569 |
if reference.is_empty() && note.is_empty() { |
| 2570 |
bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT"); |
| 2571 |
} |
| 2572 |
let card: hub_api::ProjectCard = |
| 2573 |
c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?; |
| 2574 |
if json { |
| 2575 |
println!("{}", serde_json::to_string(&card)?); |
| 2576 |
} else { |
| 2577 |
println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference }); |
| 2578 |
} |
| 2579 |
} |
| 2580 |
ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) { |
| 2581 |
(Some(card), None) => { |
| 2582 |
c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?; |
| 2583 |
println!("{} card {card} moved to {column}", ui::ok("✔")); |
| 2584 |
} |
| 2585 |
(None, Some(from)) => { |
| 2586 |
let r: hub_api::CardsMoved = c.send( |
| 2587 |
"POST", |
| 2588 |
&format!("{base}/{number}/cards/move"), |
| 2589 |
&hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run }, |
| 2590 |
)?; |
| 2591 |
if json { |
| 2592 |
println!("{}", serde_json::to_string(&r)?); |
| 2593 |
return Ok(0); |
| 2594 |
} |
| 2595 |
let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() }; |
| 2596 |
for m in &r.moved { |
| 2597 |
println!(" {} {} {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title)); |
| 2598 |
} |
| 2599 |
let verb = if dry_run { "would move" } else { "moved" }; |
| 2600 |
println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len()); |
| 2601 |
} |
| 2602 |
_ => bail!("name a card, or --from COLUMN to move every card of a column"), |
| 2603 |
}, |
| 2604 |
ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => { |
| 2605 |
let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) { |
| 2606 |
None => None, |
| 2607 |
Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?), |
| 2608 |
}; |
| 2609 |
let r: hub_api::CardsArchived = c.send( |
| 2610 |
"POST", |
| 2611 |
&format!("{base}/{number}/cards/archive"), |
| 2612 |
&hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run }, |
| 2613 |
)?; |
| 2614 |
if json { |
| 2615 |
println!("{}", serde_json::to_string(&r)?); |
| 2616 |
return Ok(0); |
| 2617 |
} |
| 2618 |
let verb = if dry_run { "would archive" } else { "archived" }; |
| 2619 |
for a in &r.archived { |
| 2620 |
let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() }; |
| 2621 |
println!(" {verb} {name} {}", ui::dim(&a.title)); |
| 2622 |
} |
| 2623 |
println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len()); |
| 2624 |
} |
| 2625 |
ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => { |
| 2626 |
c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?; |
| 2627 |
println!("{} card {card} restored", ui::ok("✔")); |
| 2628 |
} |
| 2629 |
ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => { |
| 2630 |
c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?; |
| 2631 |
println!("{} card {card} removed", ui::ok("✔")); |
| 2632 |
} |
| 2633 |
} |
| 2634 |
Ok(0) |
| 2635 |
} |
| 2636 |
|
| 2637 |
fn milestone_line(m: &hub_api::Milestone) -> String { |
| 2638 |
let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") }; |
| 2639 |
let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default(); |
| 2640 |
format!("{glyph} {} {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due)) |
| 2641 |
} |
| 2642 |
|
| 2643 |
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> { |
| 2644 |
let base = t.repo_path()?; |
| 2645 |
let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> { |
| 2646 |
let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?; |
| 2647 |
if json { |
| 2648 |
println!("{}", serde_json::to_string(&m)?); |
| 2649 |
} else { |
| 2650 |
println!("{} {verb} milestone {}", ui::ok("✔"), m.title); |
| 2651 |
} |
| 2652 |
Ok(()) |
| 2653 |
}; |
| 2654 |
match cmd { |
| 2655 |
MilestoneCmd::List => { |
| 2656 |
let path = format!("{base}/milestones"); |
| 2657 |
if json { |
| 2658 |
println!("{}", c.get_text(&path)?); |
| 2659 |
return Ok(0); |
| 2660 |
} |
| 2661 |
let list: Vec<hub_api::Milestone> = c.get(&path)?; |
| 2662 |
if list.is_empty() { |
| 2663 |
println!("{}", ui::dim("No milestones.")); |
| 2664 |
} |
| 2665 |
for m in &list { |
| 2666 |
println!("{}", milestone_line(m)); |
| 2667 |
} |
| 2668 |
} |
| 2669 |
MilestoneCmd::Create { title, description, due } => { |
| 2670 |
let m: hub_api::Milestone = |
| 2671 |
c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?; |
| 2672 |
if json { |
| 2673 |
println!("{}", serde_json::to_string(&m)?); |
| 2674 |
} else { |
| 2675 |
println!("{} milestone {}", ui::ok("✔"), m.title); |
| 2676 |
} |
| 2677 |
} |
| 2678 |
MilestoneCmd::Edit { title, rename, description, due } => { |
| 2679 |
if rename.is_none() && description.is_none() && due.is_none() { |
| 2680 |
bail!("say what to change: --rename, --description or --due"); |
| 2681 |
} |
| 2682 |
edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?; |
| 2683 |
} |
| 2684 |
MilestoneCmd::Close { title } => { |
| 2685 |
edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?; |
| 2686 |
} |
| 2687 |
MilestoneCmd::Reopen { title } => { |
| 2688 |
edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?; |
| 2689 |
} |
| 2690 |
} |
| 2691 |
Ok(0) |
| 2692 |
} |
| 2693 |
|
| 2694 |
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> { |
| 2695 |
let base = t.repo_path()?; |
| 2696 |
match cmd { |
| 2697 |
TagCmd::List => { |
| 2698 |
let path = format!("{base}/tags"); |
| 2699 |
if json { |
| 2700 |
println!("{}", c.get_text(&path)?); |
| 2701 |
return Ok(0); |
| 2702 |
} |
| 2703 |
let tags: Vec<Tag> = c.get(&path)?; |
| 2704 |
if tags.is_empty() { |
| 2705 |
println!("{}", ui::dim("no tags")); |
| 2706 |
} |
| 2707 |
for t in tags { |
| 2708 |
let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect(); |
| 2709 |
let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into()); |
| 2710 |
println!("{} {} {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer)); |
| 2711 |
} |
| 2712 |
} |
| 2713 |
TagCmd::Create { name, target, message } => { |
| 2714 |
let new = hub_api::NewTag { name, target, message }; |
| 2715 |
let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?; |
| 2716 |
if json { |
| 2717 |
println!("{}", serde_json::to_string(&made)?); |
| 2718 |
} else { |
| 2719 |
println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len()))); |
| 2720 |
} |
| 2721 |
} |
| 2722 |
TagCmd::Delete { name, reason } => { |
| 2723 |
let reason = reason.unwrap_or_default(); |
| 2724 |
c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?; |
| 2725 |
if json { |
| 2726 |
println!("{}", serde_json::json!({ "withdrawn": name })); |
| 2727 |
} else { |
| 2728 |
println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)")); |
| 2729 |
} |
| 2730 |
} |
| 2731 |
} |
| 2732 |
Ok(0) |
| 2733 |
} |
| 2734 |
|
| 2735 |
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> { |
| 2736 |
let base = t.repo_path()?; |
| 2737 |
match cmd { |
| 2738 |
ReleaseCmd::List => { |
| 2739 |
let path = format!("{base}/releases"); |
| 2740 |
if json { |
| 2741 |
println!("{}", c.get_text(&path)?); |
| 2742 |
return Ok(0); |
| 2743 |
} |
| 2744 |
let list: Vec<Release> = c.get(&path)?; |
| 2745 |
if list.is_empty() { |
| 2746 |
println!("{}", ui::dim("No releases.")); |
| 2747 |
} |
| 2748 |
for r in &list { |
| 2749 |
println!( |
| 2750 |
"{} {} {}{}", |
| 2751 |
if r.latest { ui::ok("●") } else { ui::dim("○") }, |
| 2752 |
ui::strong(&r.tag), |
| 2753 |
r.title, |
| 2754 |
ui::dim(&format!( |
| 2755 |
" · {} asset{} · {}", |
| 2756 |
r.assets.len(), |
| 2757 |
if r.assets.len() == 1 { "" } else { "s" }, |
| 2758 |
ui::ago(r.created_ms) |
| 2759 |
)) |
| 2760 |
); |
| 2761 |
} |
| 2762 |
} |
| 2763 |
ReleaseCmd::Create { tag, title, notes, prerelease } => { |
| 2764 |
let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease }; |
| 2765 |
let r: Release = c.send("POST", &format!("{base}/releases"), &new)?; |
| 2766 |
if json { |
| 2767 |
println!("{}", serde_json::to_string(&r)?); |
| 2768 |
} else { |
| 2769 |
println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); |
| 2770 |
} |
| 2771 |
} |
| 2772 |
ReleaseCmd::Edit { tag, title, notes, prerelease } => { |
| 2773 |
let notes = match notes.as_deref() { |
| 2774 |
Some("-") => Some(body_of(None, Some("-".into()))?), |
| 2775 |
_ => notes, |
| 2776 |
}; |
| 2777 |
if title.is_none() && notes.is_none() && prerelease.is_none() { |
| 2778 |
bail!("say what to change: --title, --notes or --prerelease"); |
| 2779 |
} |
| 2780 |
let edit = hub_api::ReleaseEdit { title, notes, prerelease }; |
| 2781 |
let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?; |
| 2782 |
if json { |
| 2783 |
println!("{}", serde_json::to_string(&r)?); |
| 2784 |
} else { |
| 2785 |
println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); |
| 2786 |
} |
| 2787 |
} |
| 2788 |
ReleaseCmd::Upload { tag, files } => { |
| 2789 |
if files.is_empty() { |
| 2790 |
bail!("name the files to attach"); |
| 2791 |
} |
| 2792 |
for f in files { |
| 2793 |
let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string(); |
| 2794 |
let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?; |
| 2795 |
c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?; |
| 2796 |
println!("{} attached {name} to {tag}", ui::ok("✔")); |
| 2797 |
} |
| 2798 |
} |
| 2799 |
ReleaseCmd::Trust { tag } => { |
| 2800 |
let path = format!("{base}/releases/trust/{}", enc(&tag)); |
| 2801 |
if json { |
| 2802 |
println!("{}", c.get_text(&path)?); |
| 2803 |
return Ok(0); |
| 2804 |
} |
| 2805 |
let r: serde_json::Value = c.get(&path)?; |
| 2806 |
println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"]))); |
| 2807 |
let mut worst = 0; |
| 2808 |
for ch in r["audit"].as_array().into_iter().flatten() { |
| 2809 |
let v = ch["verdict"].as_str().unwrap_or(""); |
| 2810 |
worst = worst.max(match v { |
| 2811 |
"fail" => 2, |
| 2812 |
"warn" => 1, |
| 2813 |
_ => 0, |
| 2814 |
}); |
| 2815 |
let g = match v { |
| 2816 |
"pass" => ui::ok("✔"), |
| 2817 |
"warn" => ui::warn("!"), |
| 2818 |
_ => ui::bad("✘"), |
| 2819 |
}; |
| 2820 |
println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or(""))); |
| 2821 |
} |
| 2822 |
return Ok(if worst == 2 { 1 } else { 0 }); |
| 2823 |
} |
| 2824 |
} |
| 2825 |
Ok(0) |
| 2826 |
} |
| 2827 |
|
| 2828 |
#[cfg(test)] |
| 2829 |
mod tests { |
| 2830 |
|
| 2831 |
#[test] |
| 2832 |
fn job_timings_and_report_commands_read_plainly() { |
| 2833 |
use clap::Parser; |
| 2834 |
let job = hub_api::FlowJob { |
| 2835 |
name: "perf".into(), |
| 2836 |
status: "passed".into(), |
| 2837 |
depends_on: vec![], |
| 2838 |
runner: "earth-1".into(), |
| 2839 |
exit_code: Some(0), |
| 2840 |
error: String::new(), |
| 2841 |
started_ms: Some(13_000), |
| 2842 |
finished_ms: Some(200_000), |
| 2843 |
log_lines: 10, |
| 2844 |
waiting: String::new(), |
| 2845 |
placed: String::new(), |
| 2846 |
approval: String::new(), |
| 2847 |
queued_ms: Some(1_000), |
| 2848 |
ready_ms: Some(12_500), |
| 2849 |
phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }], |
| 2850 |
peak_disk_mib: Some(2150), |
| 2851 |
peak_memory_mib: Some(900), |
| 2852 |
}; |
| 2853 |
assert_eq!(super::timing_line(&job), "waited 12.0 s · image 850 ms · run 2 min 5 s · peak disk 2.1 GiB, memory 900 MiB"); |
| 2854 |
let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job }; |
| 2855 |
assert_eq!(super::timing_line(&bare), ""); |
| 2856 |
assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv"); |
| 2857 |
|
| 2858 |
let cli = |
| 2859 |
super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap(); |
| 2860 |
let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") }; |
| 2861 |
assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false)); |
| 2862 |
assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other"); |
| 2863 |
assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file"); |
| 2864 |
let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap(); |
| 2865 |
assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } })); |
| 2866 |
assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok()); |
| 2867 |
} |
| 2868 |
|
| 2869 |
#[test] |
| 2870 |
fn runner_update_scopes_resolve_by_name_or_id() { |
| 2871 |
let all = hub_api::RunnerUpdates { |
| 2872 |
repo: String::new(), |
| 2873 |
settings: vec![], |
| 2874 |
groups: vec![hub_api::RunnerGroup { |
| 2875 |
id: 4, |
| 2876 |
owner: "acme".into(), |
| 2877 |
name: "canary".into(), |
| 2878 |
percent: None, |
| 2879 |
members: vec![], |
| 2880 |
wave: None, |
| 2881 |
}], |
| 2882 |
runners: vec![], |
| 2883 |
holds: vec![], |
| 2884 |
}; |
| 2885 |
assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new())); |
| 2886 |
assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string())); |
| 2887 |
for g in ["group:canary", "group:acme/canary", "group:4"] { |
| 2888 |
assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}"); |
| 2889 |
} |
| 2890 |
assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner")); |
| 2891 |
assert!(update_scope("everyone", &all).is_err()); |
| 2892 |
assert_eq!(switch(Some("inherit")).unwrap(), Some(None)); |
| 2893 |
assert!(switch(Some("yes")).is_err()); |
| 2894 |
} |
| 2895 |
use super::*; |
| 2896 |
|
| 2897 |
|
| 2898 |
|
| 2899 |
#[test] |
| 2900 |
fn drop_commands_parse() { |
| 2901 |
let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap(); |
| 2902 |
match cli.cmd { |
| 2903 |
Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => { |
| 2904 |
assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]); |
| 2905 |
assert!(secret); |
| 2906 |
assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes"))); |
| 2907 |
} |
| 2908 |
_ => panic!("not drop create"), |
| 2909 |
} |
| 2910 |
assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file"); |
| 2911 |
match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() { |
| 2912 |
Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => { |
| 2913 |
assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05"))); |
| 2914 |
assert!(channel.is_none() && dry_run.is_none()); |
| 2915 |
} |
| 2916 |
_ => panic!("not runner-updates set"), |
| 2917 |
} |
| 2918 |
assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None })); |
| 2919 |
match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() { |
| 2920 |
Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)), |
| 2921 |
_ => panic!("not drop list"), |
| 2922 |
} |
| 2923 |
match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd { |
| 2924 |
Cmd::Drop { cmd: DropCmd::View { id, file } } => { |
| 2925 |
assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt"))) |
| 2926 |
} |
| 2927 |
_ => panic!("not drop view"), |
| 2928 |
} |
| 2929 |
assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } })); |
| 2930 |
for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] { |
| 2931 |
assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}"); |
| 2932 |
} |
| 2933 |
assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something"); |
| 2934 |
match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd { |
| 2935 |
Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"), |
| 2936 |
_ => panic!("not drop comment"), |
| 2937 |
} |
| 2938 |
assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567"); |
| 2939 |
assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567"); |
| 2940 |
assert!(drop_id("andy/notes").is_err()); |
| 2941 |
} |
| 2942 |
} |