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