| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `braid hub issue` and `label`: a repository's issues and labels. |
| 5 | //! |
| 6 | //! Each is a request of section 18 of `docs/hub.md`. The repository is |
| 7 | //! `-R OWNER/NAME`, else the one this repository is linked to. A text comes |
| 8 | //! from `--body`, or from `--body-file` (`-` reads standard input), at most |
| 9 | //! 64 KiB. Opening an issue and commenting send an `Idempotency-Key`, and |
| 10 | //! are sent once more with the same key when the answer was lost, so that |
| 11 | //! they are never done twice. With `--json` each prints what the hub |
| 12 | //! answered. Exit statuses as the other hub commands: 0 done, 1 refused, |
| 13 | //! 3 when the hub could not be reached or failed. |
| 14 | //! |
| 15 | //! Titles, texts, comments, logins and labels are anyone's words: printed |
| 16 | //! without `--json`, they go through [`shown`], so that no control |
| 17 | //! character of theirs reaches a terminal raw. |
| 18 | |
| 19 | use std::fmt::Write; |
| 20 | use std::path::PathBuf; |
| 21 | use std::process::ExitCode; |
| 22 | |
| 23 | use anyhow::{Result, bail}; |
| 24 | use braid_hubproto::RepoPath; |
| 25 | use braid_hubproto::issues::{Comment, Comments, Issue, Issues, Label, Labels}; |
| 26 | use clap::{Args, Subcommand, ValueEnum}; |
| 27 | use serde::de::DeserializeOwned; |
| 28 | use serde_json::{Value, json}; |
| 29 | |
| 30 | use super::http::HttpHub; |
| 31 | use super::remote::{HubError, shown}; |
| 32 | use super::social_common::{ |
| 33 | HubRepoArg, agent, body_text, exit_for, hub_repo, idempotency_key, print, |
| 34 | }; |
| 35 | use crate::Cli; |
| 36 | |
| 37 | /// A text of several lines from the hub, as braid prints it: each line as |
| 38 | /// [`shown`] shows text, its line breaks and tabs kept. |
| 39 | fn shown_lines(text: &str) -> String { |
| 40 | text.split('\n') |
| 41 | .map(|line| line.split('\t').map(shown).collect::<Vec<_>>().join("\t")) |
| 42 | .collect::<Vec<_>>() |
| 43 | .join("\n") |
| 44 | } |
| 45 | |
| 46 | /// What a command answers when the hub refused it or could not be |
| 47 | /// reached: the error, and the exit status it calls for. |
| 48 | fn failed(err: &HubError) -> ExitCode { |
| 49 | eprintln!("braid: error: {err}"); |
| 50 | ExitCode::from(exit_for(err)) |
| 51 | } |
| 52 | |
| 53 | /// `text` as a value of a query string, or a segment of a path: |
| 54 | /// everything but letters, digits and `-._~` percent-encoded. |
| 55 | fn encoded(text: &str) -> String { |
| 56 | let mut out = String::with_capacity(text.len()); |
| 57 | for byte in text.bytes() { |
| 58 | if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { |
| 59 | out.push(char::from(byte)); |
| 60 | } else { |
| 61 | let _ = write!(out, "%{byte:02X}"); |
| 62 | } |
| 63 | } |
| 64 | out |
| 65 | } |
| 66 | |
| 67 | /// Sends a request that creates something, with an `Idempotency-Key`, and |
| 68 | /// sends it once more with the same key when the answer was lost: the hub |
| 69 | /// then gives the first answer again rather than doing it twice. |
| 70 | fn create<T: DeserializeOwned>(hub: &HttpHub, route: &str, body: &Value) -> Result<T, HubError> { |
| 71 | let key = idempotency_key(); |
| 72 | let headers = [("Idempotency-Key", key.as_str())]; |
| 73 | match hub.call_json("POST", route, &headers, Some(body)) { |
| 74 | Err(err) if err.may_have_happened() => hub.call_json("POST", route, &headers, Some(body)), |
| 75 | answer => answer, |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// An issue in a line: its number, title, labels and state. |
| 80 | fn line(issue: &Issue) -> String { |
| 81 | let mut out = format!("#{} {}", issue.number, shown(&issue.title)); |
| 82 | if !issue.labels.is_empty() { |
| 83 | let _ = write!(out, " [{}]", shown(&issue.labels.join(", "))); |
| 84 | } |
| 85 | if issue.state != braid_hubproto::issues::OPEN { |
| 86 | out.push_str(" (closed)"); |
| 87 | } |
| 88 | out |
| 89 | } |
| 90 | |
| 91 | /// `hub issue`. |
| 92 | #[derive(Debug, Args)] |
| 93 | pub(crate) struct IssueArgs { |
| 94 | #[command(subcommand)] |
| 95 | pub(crate) action: IssueAction, |
| 96 | } |
| 97 | |
| 98 | /// What `hub issue` does. |
| 99 | #[derive(Debug, Subcommand)] |
| 100 | pub(crate) enum IssueAction { |
| 101 | /// List a repository's issues, newest first. |
| 102 | List(ListArgs), |
| 103 | /// Show an issue and its comments. |
| 104 | Show(ShowArgs), |
| 105 | /// Open an issue. |
| 106 | Create(CreateArgs), |
| 107 | /// Comment on an issue. |
| 108 | Comment(CommentArgs), |
| 109 | /// Close an issue. |
| 110 | Close(CloseArgs), |
| 111 | /// Open a closed issue again. |
| 112 | Reopen(NumberArgs), |
| 113 | /// Change an issue: its title, text, labels, assignees or lock. |
| 114 | Edit(EditArgs), |
| 115 | } |
| 116 | |
| 117 | /// Which issues `issue list` shows. |
| 118 | #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] |
| 119 | pub(crate) enum StateArg { |
| 120 | /// Those open. |
| 121 | Open, |
| 122 | /// Those closed. |
| 123 | Closed, |
| 124 | /// Both. |
| 125 | All, |
| 126 | } |
| 127 | |
| 128 | impl StateArg { |
| 129 | fn as_str(self) -> &'static str { |
| 130 | match self { |
| 131 | StateArg::Open => "open", |
| 132 | StateArg::Closed => "closed", |
| 133 | StateArg::All => "all", |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// What `issue list` sorts by. |
| 139 | #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] |
| 140 | pub(crate) enum SortArg { |
| 141 | /// When each was opened. |
| 142 | Created, |
| 143 | /// When each last changed. |
| 144 | Updated, |
| 145 | /// How many comments each has. |
| 146 | Comments, |
| 147 | } |
| 148 | |
| 149 | impl SortArg { |
| 150 | fn as_str(self) -> &'static str { |
| 151 | match self { |
| 152 | SortArg::Created => "created", |
| 153 | SortArg::Updated => "updated", |
| 154 | SortArg::Comments => "comments", |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// `hub issue list`. |
| 160 | #[derive(Debug, Args)] |
| 161 | pub(crate) struct ListArgs { |
| 162 | #[command(flatten)] |
| 163 | pub(crate) repo: HubRepoArg, |
| 164 | /// Which issues, by state. |
| 165 | #[arg(long, value_enum, default_value_t = StateArg::Open)] |
| 166 | pub(crate) state: StateArg, |
| 167 | /// Only those with this label; given again, with every one of them. |
| 168 | #[arg(long = "label", value_name = "LABEL")] |
| 169 | pub(crate) labels: Vec<String>, |
| 170 | /// Only those assigned to this account (`none` for nobody, `*` for |
| 171 | /// anybody). |
| 172 | #[arg(long, value_name = "LOGIN")] |
| 173 | pub(crate) assignee: Option<String>, |
| 174 | /// Only those this account opened. |
| 175 | #[arg(long, value_name = "LOGIN")] |
| 176 | pub(crate) author: Option<String>, |
| 177 | /// Only those whose title holds this text: public repositories only. |
| 178 | #[arg(long, value_name = "TEXT")] |
| 179 | pub(crate) search: Option<String>, |
| 180 | /// What sorts them, the newest or the most first. |
| 181 | #[arg(long, value_enum, default_value_t = SortArg::Created)] |
| 182 | pub(crate) sort: SortArg, |
| 183 | /// The most issues to list, 1 to 100 (default: 30). |
| 184 | #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))] |
| 185 | pub(crate) limit: Option<u32>, |
| 186 | /// Where to start: the `next` of the page before. |
| 187 | #[arg(long, value_name = "CURSOR")] |
| 188 | pub(crate) after: Option<String>, |
| 189 | } |
| 190 | |
| 191 | /// `hub issue show`. |
| 192 | #[derive(Debug, Args)] |
| 193 | pub(crate) struct ShowArgs { |
| 194 | /// The issue's number. |
| 195 | #[arg(value_name = "NUMBER")] |
| 196 | pub(crate) number: u64, |
| 197 | #[command(flatten)] |
| 198 | pub(crate) repo: HubRepoArg, |
| 199 | } |
| 200 | |
| 201 | /// A text, from the command line or a file. |
| 202 | #[derive(Debug, Args)] |
| 203 | pub(crate) struct BodyArgs { |
| 204 | /// The text, Markdown. |
| 205 | #[arg(long, value_name = "TEXT")] |
| 206 | pub(crate) body: Option<String>, |
| 207 | /// Read the text from this file; `-` reads standard input. |
| 208 | #[arg(long, value_name = "FILE")] |
| 209 | pub(crate) body_file: Option<PathBuf>, |
| 210 | } |
| 211 | |
| 212 | impl BodyArgs { |
| 213 | fn text(&self) -> Result<Option<String>> { |
| 214 | body_text(self.body.as_deref(), self.body_file.as_deref()) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// `hub issue create`. |
| 219 | #[derive(Debug, Args)] |
| 220 | pub(crate) struct CreateArgs { |
| 221 | #[command(flatten)] |
| 222 | pub(crate) repo: HubRepoArg, |
| 223 | /// Its title, one line. |
| 224 | #[arg(long, value_name = "TITLE")] |
| 225 | pub(crate) title: String, |
| 226 | #[command(flatten)] |
| 227 | pub(crate) body: BodyArgs, |
| 228 | /// A label to give it, by its name; given again, more (the |
| 229 | /// repository's writers only). |
| 230 | #[arg(long = "label", value_name = "LABEL")] |
| 231 | pub(crate) labels: Vec<String>, |
| 232 | /// An account to assign it to; given again, more (the repository's |
| 233 | /// writers only). |
| 234 | #[arg(long = "assignee", value_name = "LOGIN")] |
| 235 | pub(crate) assignees: Vec<String>, |
| 236 | } |
| 237 | |
| 238 | /// `hub issue comment`. |
| 239 | #[derive(Debug, Args)] |
| 240 | pub(crate) struct CommentArgs { |
| 241 | /// The issue's number. |
| 242 | #[arg(value_name = "NUMBER")] |
| 243 | pub(crate) number: u64, |
| 244 | #[command(flatten)] |
| 245 | pub(crate) repo: HubRepoArg, |
| 246 | #[command(flatten)] |
| 247 | pub(crate) body: BodyArgs, |
| 248 | } |
| 249 | |
| 250 | /// What a closed issue was closed as. |
| 251 | #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] |
| 252 | pub(crate) enum ReasonArg { |
| 253 | /// Done. |
| 254 | Completed, |
| 255 | /// Not to be done. |
| 256 | NotPlanned, |
| 257 | } |
| 258 | |
| 259 | impl ReasonArg { |
| 260 | fn as_str(self) -> &'static str { |
| 261 | match self { |
| 262 | ReasonArg::Completed => braid_hubproto::issues::COMPLETED, |
| 263 | ReasonArg::NotPlanned => braid_hubproto::issues::NOT_PLANNED, |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// `hub issue close`. |
| 269 | #[derive(Debug, Args)] |
| 270 | pub(crate) struct CloseArgs { |
| 271 | /// The issue's number. |
| 272 | #[arg(value_name = "NUMBER")] |
| 273 | pub(crate) number: u64, |
| 274 | #[command(flatten)] |
| 275 | pub(crate) repo: HubRepoArg, |
| 276 | /// What it is closed as. |
| 277 | #[arg(long, value_enum, default_value_t = ReasonArg::Completed)] |
| 278 | pub(crate) reason: ReasonArg, |
| 279 | } |
| 280 | |
| 281 | /// `hub issue reopen`. |
| 282 | #[derive(Debug, Args)] |
| 283 | pub(crate) struct NumberArgs { |
| 284 | /// The issue's number. |
| 285 | #[arg(value_name = "NUMBER")] |
| 286 | pub(crate) number: u64, |
| 287 | #[command(flatten)] |
| 288 | pub(crate) repo: HubRepoArg, |
| 289 | } |
| 290 | |
| 291 | /// `hub issue edit`. |
| 292 | #[derive(Debug, Args)] |
| 293 | pub(crate) struct EditArgs { |
| 294 | /// The issue's number. |
| 295 | #[arg(value_name = "NUMBER")] |
| 296 | pub(crate) number: u64, |
| 297 | #[command(flatten)] |
| 298 | pub(crate) repo: HubRepoArg, |
| 299 | /// A new title. |
| 300 | #[arg(long, value_name = "TITLE")] |
| 301 | pub(crate) title: Option<String>, |
| 302 | #[command(flatten)] |
| 303 | pub(crate) body: BodyArgs, |
| 304 | /// A label to add; given again, more. |
| 305 | #[arg(long = "add-label", value_name = "LABEL")] |
| 306 | pub(crate) add_labels: Vec<String>, |
| 307 | /// A label to take off; given again, more. |
| 308 | #[arg(long = "remove-label", value_name = "LABEL")] |
| 309 | pub(crate) remove_labels: Vec<String>, |
| 310 | /// An account to assign it to; given again, more. |
| 311 | #[arg(long = "add-assignee", value_name = "LOGIN")] |
| 312 | pub(crate) add_assignees: Vec<String>, |
| 313 | /// An account to take off it; given again, more. |
| 314 | #[arg(long = "remove-assignee", value_name = "LOGIN")] |
| 315 | pub(crate) remove_assignees: Vec<String>, |
| 316 | /// Let only the repository's writers comment on it. |
| 317 | #[arg(long, conflicts_with = "unlock")] |
| 318 | pub(crate) lock: bool, |
| 319 | /// Let everyone who may comment do so again. |
| 320 | #[arg(long)] |
| 321 | pub(crate) unlock: bool, |
| 322 | } |
| 323 | |
| 324 | pub(crate) fn issue(cli: &Cli, args: &IssueArgs) -> Result<ExitCode> { |
| 325 | match &args.action { |
| 326 | IssueAction::List(args) => list(cli, args), |
| 327 | IssueAction::Show(args) => show(cli, args), |
| 328 | IssueAction::Create(args) => create_issue(cli, args), |
| 329 | IssueAction::Comment(args) => comment(cli, args), |
| 330 | IssueAction::Close(args) => { |
| 331 | let body = json!({"state": "closed", "state_reason": args.reason.as_str()}); |
| 332 | change(cli, &args.repo, args.number, &body, |path, issue| { |
| 333 | format!( |
| 334 | "Closed {path}#{} as {}.", |
| 335 | issue.number, |
| 336 | args.reason.as_str().replace('_', " ") |
| 337 | ) |
| 338 | }) |
| 339 | } |
| 340 | IssueAction::Reopen(args) => change( |
| 341 | cli, |
| 342 | &args.repo, |
| 343 | args.number, |
| 344 | &json!({"state": "open"}), |
| 345 | |path, issue| format!("Reopened {path}#{}.", issue.number), |
| 346 | ), |
| 347 | IssueAction::Edit(args) => edit(cli, args), |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// The route of the issue `number` of `path`. |
| 352 | fn issue_route(path: &RepoPath, number: u64) -> String { |
| 353 | format!("{}/issues/{number}", path.api_path()) |
| 354 | } |
| 355 | |
| 356 | fn list(cli: &Cli, args: &ListArgs) -> Result<ExitCode> { |
| 357 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 358 | let mut query = vec![ |
| 359 | format!("state={}", args.state.as_str()), |
| 360 | format!("sort={}", args.sort.as_str()), |
| 361 | ]; |
| 362 | if !args.labels.is_empty() { |
| 363 | query.push(format!("labels={}", encoded(&args.labels.join(",")))); |
| 364 | } |
| 365 | for (name, value) in [ |
| 366 | ("assignee", &args.assignee), |
| 367 | ("author", &args.author), |
| 368 | ("q", &args.search), |
| 369 | ("after", &args.after), |
| 370 | ] { |
| 371 | if let Some(value) = value { |
| 372 | query.push(format!("{name}={}", encoded(value))); |
| 373 | } |
| 374 | } |
| 375 | if let Some(limit) = args.limit { |
| 376 | query.push(format!("limit={limit}")); |
| 377 | } |
| 378 | let route = format!("{}/issues?{}", path.api_path(), query.join("&")); |
| 379 | let page: Issues = match hub.call_json("GET", &route, &[], None) { |
| 380 | Ok(page) => page, |
| 381 | Err(err) => return Ok(failed(&err)), |
| 382 | }; |
| 383 | print(cli, &serde_json::to_value(&page)?, || { |
| 384 | let mut out = String::new(); |
| 385 | if page.issues.is_empty() { |
| 386 | out.push_str("No issues."); |
| 387 | } |
| 388 | for issue in &page.issues { |
| 389 | if !out.is_empty() { |
| 390 | out.push('\n'); |
| 391 | } |
| 392 | out.push_str(&line(issue)); |
| 393 | let _ = write!(out, ", by {}", shown(&issue.author)); |
| 394 | if issue.comments > 0 { |
| 395 | let noun = if issue.comments == 1 { |
| 396 | "comment" |
| 397 | } else { |
| 398 | "comments" |
| 399 | }; |
| 400 | let _ = write!(out, ", {} {noun}", issue.comments); |
| 401 | } |
| 402 | } |
| 403 | if let Some(next) = &page.next { |
| 404 | let _ = write!( |
| 405 | out, |
| 406 | "\nMore: braid hub issue list -R {path} --state {} --after {}", |
| 407 | args.state.as_str(), |
| 408 | shown(next) |
| 409 | ); |
| 410 | } |
| 411 | out |
| 412 | })?; |
| 413 | Ok(ExitCode::SUCCESS) |
| 414 | } |
| 415 | |
| 416 | fn show(cli: &Cli, args: &ShowArgs) -> Result<ExitCode> { |
| 417 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 418 | let route = issue_route(&path, args.number); |
| 419 | let mut issue: Issue = match hub.call_json("GET", &route, &[], None) { |
| 420 | Ok(issue) => issue, |
| 421 | Err(err) => return Ok(failed(&err)), |
| 422 | }; |
| 423 | let comments: Comments = |
| 424 | match hub.call_json("GET", &format!("{route}/comments?limit=100"), &[], None) { |
| 425 | Ok(comments) => comments, |
| 426 | Err(err) => return Ok(failed(&err)), |
| 427 | }; |
| 428 | issue.html = None; |
| 429 | let value = json!({"issue": issue, "comments": comments.comments, "next": comments.next}); |
| 430 | print(cli, &value, || { |
| 431 | let mut out = format!("{path}{}\n", line(&issue)); |
| 432 | let _ = writeln!( |
| 433 | out, |
| 434 | "Opened by {} on {}", |
| 435 | shown(&issue.author), |
| 436 | shown(&issue.created) |
| 437 | ); |
| 438 | if !issue.assignees.is_empty() { |
| 439 | let _ = writeln!(out, "Assigned to {}", shown(&issue.assignees.join(", "))); |
| 440 | } |
| 441 | if issue.locked { |
| 442 | out.push_str("Locked: only the repository's writers comment on it.\n"); |
| 443 | } |
| 444 | if !issue.body.trim().is_empty() { |
| 445 | let _ = write!(out, "\n{}\n", shown_lines(issue.body.trim_end())); |
| 446 | } |
| 447 | for comment in &comments.comments { |
| 448 | let _ = write!( |
| 449 | out, |
| 450 | "\n--- {} on {}", |
| 451 | shown(&comment.author), |
| 452 | shown(&comment.created) |
| 453 | ); |
| 454 | match &comment.hidden { |
| 455 | Some(reason) if comment.body.is_empty() => { |
| 456 | let _ = write!(out, " (hidden: {})", shown(reason)); |
| 457 | } |
| 458 | _ => { |
| 459 | let _ = write!(out, "\n{}", shown_lines(comment.body.trim_end())); |
| 460 | } |
| 461 | } |
| 462 | out.push('\n'); |
| 463 | } |
| 464 | if let Some(next) = &comments.next { |
| 465 | let _ = write!( |
| 466 | out, |
| 467 | "\nMore comments: braid hub api GET '{route}/comments?after={}'", |
| 468 | shown(next) |
| 469 | ); |
| 470 | } |
| 471 | out.trim_end().to_owned() |
| 472 | })?; |
| 473 | Ok(ExitCode::SUCCESS) |
| 474 | } |
| 475 | |
| 476 | fn create_issue(cli: &Cli, args: &CreateArgs) -> Result<ExitCode> { |
| 477 | let body = args.body.text()?; |
| 478 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 479 | let mut request = json!({ "title": args.title }); |
| 480 | if let Some(body) = body { |
| 481 | request["body"] = json!(body); |
| 482 | } |
| 483 | if !args.labels.is_empty() { |
| 484 | request["labels"] = json!(args.labels); |
| 485 | } |
| 486 | if !args.assignees.is_empty() { |
| 487 | request["assignees"] = json!(args.assignees); |
| 488 | } |
| 489 | if let Some(agent) = agent(cli) { |
| 490 | request["agent"] = json!(agent); |
| 491 | } |
| 492 | let mut issue: Issue = match create(&hub, &format!("{}/issues", path.api_path()), &request) { |
| 493 | Ok(issue) => issue, |
| 494 | Err(err) => return Ok(failed(&err)), |
| 495 | }; |
| 496 | issue.html = None; |
| 497 | print(cli, &serde_json::to_value(&issue)?, || { |
| 498 | format!("Opened {path}#{}: {}", issue.number, shown(&issue.title)) |
| 499 | })?; |
| 500 | Ok(ExitCode::SUCCESS) |
| 501 | } |
| 502 | |
| 503 | fn comment(cli: &Cli, args: &CommentArgs) -> Result<ExitCode> { |
| 504 | let Some(body) = args.body.text()? else { |
| 505 | bail!("a comment needs its text: give --body, or --body-file (- reads standard input)"); |
| 506 | }; |
| 507 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 508 | let mut request = json!({ "body": body }); |
| 509 | if let Some(agent) = agent(cli) { |
| 510 | request["agent"] = json!(agent); |
| 511 | } |
| 512 | let route = format!("{}/comments", issue_route(&path, args.number)); |
| 513 | let mut said: Comment = match create(&hub, &route, &request) { |
| 514 | Ok(said) => said, |
| 515 | Err(err) => return Ok(failed(&err)), |
| 516 | }; |
| 517 | said.html = None; |
| 518 | print(cli, &serde_json::to_value(&said)?, || { |
| 519 | format!("Commented on {path}#{}.", args.number) |
| 520 | })?; |
| 521 | Ok(ExitCode::SUCCESS) |
| 522 | } |
| 523 | |
| 524 | /// Changes the issue `number` as `body` says, and prints it. |
| 525 | fn change( |
| 526 | cli: &Cli, |
| 527 | repo: &HubRepoArg, |
| 528 | number: u64, |
| 529 | body: &Value, |
| 530 | text: impl FnOnce(&RepoPath, &Issue) -> String, |
| 531 | ) -> Result<ExitCode> { |
| 532 | let (hub, path) = hub_repo(cli, repo.hub_repo.as_deref())?; |
| 533 | let mut issue: Issue = |
| 534 | match hub.call_json("PATCH", &issue_route(&path, number), &[], Some(body)) { |
| 535 | Ok(issue) => issue, |
| 536 | Err(err) => return Ok(failed(&err)), |
| 537 | }; |
| 538 | issue.html = None; |
| 539 | print(cli, &serde_json::to_value(&issue)?, || text(&path, &issue))?; |
| 540 | Ok(ExitCode::SUCCESS) |
| 541 | } |
| 542 | |
| 543 | /// `held`, with `added` and without `removed`, compared without regard to |
| 544 | /// case. |
| 545 | fn changed_list(held: &[String], added: &[String], removed: &[String]) -> Vec<String> { |
| 546 | let mut list: Vec<String> = held |
| 547 | .iter() |
| 548 | .filter(|item| !removed.iter().any(|gone| gone.eq_ignore_ascii_case(item))) |
| 549 | .cloned() |
| 550 | .collect(); |
| 551 | for item in added { |
| 552 | if !list.iter().any(|kept| kept.eq_ignore_ascii_case(item)) { |
| 553 | list.push(item.clone()); |
| 554 | } |
| 555 | } |
| 556 | list |
| 557 | } |
| 558 | |
| 559 | fn edit(cli: &Cli, args: &EditArgs) -> Result<ExitCode> { |
| 560 | let body = args.body.text()?; |
| 561 | let mut request = json!({}); |
| 562 | if let Some(title) = &args.title { |
| 563 | request["title"] = json!(title); |
| 564 | } |
| 565 | if let Some(body) = body { |
| 566 | request["body"] = json!(body); |
| 567 | } |
| 568 | if args.lock || args.unlock { |
| 569 | request["locked"] = json!(args.lock); |
| 570 | } |
| 571 | let labels = !args.add_labels.is_empty() || !args.remove_labels.is_empty(); |
| 572 | let assignees = !args.add_assignees.is_empty() || !args.remove_assignees.is_empty(); |
| 573 | if labels || assignees { |
| 574 | // The hub takes the whole lists: the issue's, as they are now, |
| 575 | // changed as asked. |
| 576 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 577 | let issue: Issue = match hub.call_json("GET", &issue_route(&path, args.number), &[], None) { |
| 578 | Ok(issue) => issue, |
| 579 | Err(err) => return Ok(failed(&err)), |
| 580 | }; |
| 581 | if labels { |
| 582 | request["labels"] = json!(changed_list( |
| 583 | &issue.labels, |
| 584 | &args.add_labels, |
| 585 | &args.remove_labels |
| 586 | )); |
| 587 | } |
| 588 | if assignees { |
| 589 | request["assignees"] = json!(changed_list( |
| 590 | &issue.assignees, |
| 591 | &args.add_assignees, |
| 592 | &args.remove_assignees |
| 593 | )); |
| 594 | } |
| 595 | } |
| 596 | if request.as_object().is_some_and(serde_json::Map::is_empty) { |
| 597 | bail!( |
| 598 | "nothing to change: give --title, --body, --add-label, --remove-label, --add-assignee, --remove-assignee, --lock or --unlock" |
| 599 | ); |
| 600 | } |
| 601 | change(cli, &args.repo, args.number, &request, |path, issue| { |
| 602 | format!("Changed {path}#{}.", issue.number) |
| 603 | }) |
| 604 | } |
| 605 | |
| 606 | /// `hub label`. |
| 607 | #[derive(Debug, Args)] |
| 608 | pub(crate) struct LabelArgs { |
| 609 | #[command(subcommand)] |
| 610 | pub(crate) action: LabelAction, |
| 611 | } |
| 612 | |
| 613 | /// What `hub label` does. |
| 614 | #[derive(Debug, Subcommand)] |
| 615 | pub(crate) enum LabelAction { |
| 616 | /// List a repository's labels. |
| 617 | List(LabelListArgs), |
| 618 | /// Make a label, or change one of that name. |
| 619 | Create(LabelCreateArgs), |
| 620 | /// Delete a label, and take it off every issue. |
| 621 | Delete(LabelDeleteArgs), |
| 622 | } |
| 623 | |
| 624 | /// `hub label list`. |
| 625 | #[derive(Debug, Args)] |
| 626 | pub(crate) struct LabelListArgs { |
| 627 | #[command(flatten)] |
| 628 | pub(crate) repo: HubRepoArg, |
| 629 | } |
| 630 | |
| 631 | /// `hub label create`. |
| 632 | #[derive(Debug, Args)] |
| 633 | pub(crate) struct LabelCreateArgs { |
| 634 | /// Its name: 1 to 50 characters, without commas. |
| 635 | #[arg(value_name = "NAME")] |
| 636 | pub(crate) name: String, |
| 637 | #[command(flatten)] |
| 638 | pub(crate) repo: HubRepoArg, |
| 639 | /// Its colour in the hub's palette, 0 to 11. |
| 640 | #[arg(long, value_name = "N", value_parser = clap::value_parser!(u8).range(0..=11))] |
| 641 | pub(crate) color: Option<u8>, |
| 642 | /// What it means. |
| 643 | #[arg(long, value_name = "TEXT")] |
| 644 | pub(crate) description: Option<String>, |
| 645 | } |
| 646 | |
| 647 | /// `hub label delete`. |
| 648 | #[derive(Debug, Args)] |
| 649 | pub(crate) struct LabelDeleteArgs { |
| 650 | /// Its name. |
| 651 | #[arg(value_name = "NAME")] |
| 652 | pub(crate) name: String, |
| 653 | #[command(flatten)] |
| 654 | pub(crate) repo: HubRepoArg, |
| 655 | } |
| 656 | |
| 657 | pub(crate) fn label(cli: &Cli, args: &LabelArgs) -> Result<ExitCode> { |
| 658 | match &args.action { |
| 659 | LabelAction::List(args) => { |
| 660 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 661 | let route = format!("{}/labels", path.api_path()); |
| 662 | let labels: Labels = match hub.call_json("GET", &route, &[], None) { |
| 663 | Ok(labels) => labels, |
| 664 | Err(err) => return Ok(failed(&err)), |
| 665 | }; |
| 666 | print(cli, &serde_json::to_value(&labels)?, || { |
| 667 | let lines: Vec<String> = labels |
| 668 | .labels |
| 669 | .iter() |
| 670 | .map(|label| { |
| 671 | if label.description.is_empty() { |
| 672 | format!("{} (colour {})", shown(&label.name), label.color) |
| 673 | } else { |
| 674 | format!( |
| 675 | "{} (colour {}): {}", |
| 676 | shown(&label.name), |
| 677 | label.color, |
| 678 | shown(&label.description) |
| 679 | ) |
| 680 | } |
| 681 | }) |
| 682 | .collect(); |
| 683 | if lines.is_empty() { |
| 684 | "No labels.".to_owned() |
| 685 | } else { |
| 686 | lines.join("\n") |
| 687 | } |
| 688 | })?; |
| 689 | Ok(ExitCode::SUCCESS) |
| 690 | } |
| 691 | LabelAction::Create(args) => { |
| 692 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 693 | let mut request = json!({}); |
| 694 | if let Some(color) = args.color { |
| 695 | request["color"] = json!(color); |
| 696 | } |
| 697 | if let Some(description) = &args.description { |
| 698 | request["description"] = json!(description); |
| 699 | } |
| 700 | let route = format!("{}/labels/{}", path.api_path(), encoded(&args.name)); |
| 701 | let label: Label = match hub.call_json("PUT", &route, &[], Some(&request)) { |
| 702 | Ok(label) => label, |
| 703 | Err(err) => return Ok(failed(&err)), |
| 704 | }; |
| 705 | print(cli, &serde_json::to_value(&label)?, || { |
| 706 | format!( |
| 707 | "The label {:?} of {path} has colour {}.", |
| 708 | label.name, label.color |
| 709 | ) |
| 710 | })?; |
| 711 | Ok(ExitCode::SUCCESS) |
| 712 | } |
| 713 | LabelAction::Delete(args) => { |
| 714 | let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 715 | let route = format!("{}/labels/{}", path.api_path(), encoded(&args.name)); |
| 716 | if let Err(err) = hub.call("DELETE", &route, &[], None) { |
| 717 | return Ok(failed(&err)); |
| 718 | } |
| 719 | print( |
| 720 | cli, |
| 721 | &json!({"repo": path.to_string(), "label": args.name, "deleted": true}), |
| 722 | || format!("Deleted the label {:?} of {path}.", args.name), |
| 723 | )?; |
| 724 | Ok(ExitCode::SUCCESS) |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #[cfg(test)] |
| 730 | mod tests { |
| 731 | use super::*; |
| 732 | |
| 733 | #[test] |
| 734 | fn encodings_and_lists() { |
| 735 | assert_eq!(encoded("good first issue"), "good%20first%20issue"); |
| 736 | assert_eq!(encoded("a,b/c"), "a%2Cb%2Fc"); |
| 737 | assert_eq!(encoded("icd17.4"), "icd17.4"); |
| 738 | let held = vec!["bug".to_owned(), "question".to_owned()]; |
| 739 | assert_eq!( |
| 740 | changed_list( |
| 741 | &held, |
| 742 | &["help wanted".into(), "BUG".into()], |
| 743 | &["Question".into()] |
| 744 | ), |
| 745 | ["bug", "help wanted"] |
| 746 | ); |
| 747 | let issue = Issue { |
| 748 | number: 4, |
| 749 | title: "Crash".into(), |
| 750 | labels: vec!["bug".into()], |
| 751 | state: "closed".into(), |
| 752 | ..Issue::default() |
| 753 | }; |
| 754 | assert_eq!(line(&issue), "#4 Crash [bug] (closed)"); |
| 755 | } |
| 756 | } |