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