| 1 | //! `/change` command — show a changelog entry, translated to the user's |
| 2 | //! locale when it is not English. |
| 3 | //! |
| 4 | //! Usage: `/change [version]` |
| 5 | //! |
| 6 | //! Uses the Codewhale changelog embedded at compile time. With no argument, |
| 7 | //! extracts the most recent section. With a version argument like `0.8.32`, |
| 8 | //! extracts that specific version's section. When the UI locale is not |
| 9 | //! English and the current session can reach a model, the command also fires a |
| 10 | //! `SendMessage` action that asks the model to translate the changelog into |
| 11 | //! the user's language. |
| 12 | |
| 13 | use super::DebugAction; |
| 14 | use codewhale_command_contract::facets::{CommandPresentationContext, DebugChangeProjection}; |
| 15 | use codewhale_command_contract::handler::{ |
| 16 | CommandCapabilities as Caps, CommandContexts, CommandHandler, |
| 17 | }; |
| 18 | use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand}; |
| 19 | |
| 20 | use super::CommandResult; |
| 21 | |
| 22 | /// Maximum length of the changelog excerpt we'll show inline (characters). |
| 23 | /// If the changelog section exceeds this, we truncate and show a notice. |
| 24 | /// 4096 chars is large enough for most version entries. |
| 25 | const MAX_INLINE_CHANGELOG_CHARS: usize = 4096; |
| 26 | pub struct ChangeCmd; |
| 27 | impl RegisterCommand<CommandResult> for ChangeCmd { |
| 28 | fn info() -> &'static CommandInfo { |
| 29 | &CommandInfo { |
| 30 | name: "change", |
| 31 | aliases: &[], |
| 32 | usage: "/change [version]", |
| 33 | description_key: "cmd_change_description", |
| 34 | } |
| 35 | } |
| 36 | fn handler() -> CommandHandler<CommandResult> { |
| 37 | CommandHandler::Contextual { |
| 38 | capabilities: Caps::DEBUG_CHANGE.union(Caps::PRESENTATION), |
| 39 | handler: change, |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub(super) fn change(contexts: CommandContexts<'_>, version: Option<&str>) -> CommandResult { |
| 45 | let mut parts = contexts.into_parts(); |
| 46 | let Some(change) = parts.debug_change.as_deref_mut() else { |
| 47 | return CommandResult::error("Command capability unavailable: debug_change"); |
| 48 | }; |
| 49 | let Some(presentation) = parts.presentation.as_deref_mut() else { |
| 50 | return CommandResult::error("Command capability unavailable: presentation"); |
| 51 | }; |
| 52 | match change_report(change.change_projection(), presentation, version) { |
| 53 | Ok(result) => result, |
| 54 | Err(error) => CommandResult::error(error), |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Execute the `/change` command. |
| 59 | /// |
| 60 | /// If `version` is `None`, shows the latest non-empty version section. |
| 61 | /// If `version` is `Some(v)`, shows the section for that version. |
| 62 | fn change_report( |
| 63 | projection: DebugChangeProjection, |
| 64 | presentation: &dyn CommandPresentationContext, |
| 65 | version: Option<&str>, |
| 66 | ) -> Result<CommandResult, String> { |
| 67 | let section = if let Some(ver) = version { |
| 68 | let ver = ver.trim(); |
| 69 | if ver.is_empty() { |
| 70 | extract_latest_changelog_section(projection.changelog) |
| 71 | } else { |
| 72 | extract_changelog_section_by_version(projection.changelog, ver) |
| 73 | } |
| 74 | } else { |
| 75 | extract_latest_changelog_section(projection.changelog) |
| 76 | }; |
| 77 | |
| 78 | let latest_section = match section { |
| 79 | Some(s) => s, |
| 80 | None => { |
| 81 | let msg = if let Some(ver) = version { |
| 82 | let ver = ver.trim(); |
| 83 | if ver.is_empty() { |
| 84 | "Could not find a version section in the bundled Codewhale changelog. \ |
| 85 | Expected a line starting with `## [`." |
| 86 | .to_string() |
| 87 | } else { |
| 88 | format!("Could not find version \"{ver}\" in the bundled Codewhale changelog.") |
| 89 | } |
| 90 | } else { |
| 91 | "Could not find a version section in the bundled Codewhale changelog. \ |
| 92 | Expected a line starting with `## [`." |
| 93 | .to_string() |
| 94 | }; |
| 95 | return Err(msg); |
| 96 | } |
| 97 | }; |
| 98 | |
| 99 | let header = presentation.translate("cmd_change_header", &[])?; |
| 100 | |
| 101 | let prev_hint = if let Some(prev_ver) = previous_version_hint(projection.changelog, version) { |
| 102 | let hint = |
| 103 | presentation.translate("cmd_change_previous_version", &[("version", &prev_ver)])?; |
| 104 | format!("\n\n{hint}") |
| 105 | } else { |
| 106 | String::new() |
| 107 | }; |
| 108 | |
| 109 | let section_text = inline_changelog_section(&latest_section); |
| 110 | |
| 111 | // If the user's locale is English, just display. |
| 112 | // Otherwise, also ask the model to translate. |
| 113 | Ok(if projection.is_english { |
| 114 | CommandResult::message(format!( |
| 115 | "{header}\n─────────────────────────────\n{section_text}{prev_hint}" |
| 116 | )) |
| 117 | } else if !projection.translation_available { |
| 118 | let fallback = presentation.translate("cmd_change_translation_unavailable", &[])?; |
| 119 | CommandResult::message(format!( |
| 120 | "{header}\n\ |
| 121 | ─────────────────────────────\n\ |
| 122 | {fallback}\n\n\ |
| 123 | {section_text}{prev_hint}" |
| 124 | )) |
| 125 | } else { |
| 126 | let queued = presentation.translate("cmd_change_translation_queued", &[])?; |
| 127 | let display_text = format!( |
| 128 | "{header}\n\ |
| 129 | ─────────────────────────────\n\ |
| 130 | {queued}\n\n\ |
| 131 | {section_text}{prev_hint}" |
| 132 | ); |
| 133 | let translation_source = format!("{latest_section}{prev_hint}"); |
| 134 | let lang_name = projection.translation_target; |
| 135 | |
| 136 | let translation_prompt = format!( |
| 137 | "Translate the following changelog into {lang_name}. \ |
| 138 | Keep all markdown formatting, version numbers, dates, \ |
| 139 | contributor names, and code references intact. \ |
| 140 | Output ONLY the translated changelog, no preamble or commentary.\n\n\ |
| 141 | {translation_source}" |
| 142 | ); |
| 143 | |
| 144 | CommandResult::with_message_and_action( |
| 145 | display_text, |
| 146 | DebugAction::SendMessage(translation_prompt), |
| 147 | ) |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | pub fn inline_changelog_section(section: &str) -> String { |
| 152 | let total_chars = section.chars().count(); |
| 153 | if total_chars <= MAX_INLINE_CHANGELOG_CHARS { |
| 154 | return section.to_string(); |
| 155 | } |
| 156 | |
| 157 | let truncated: String = section.chars().take(MAX_INLINE_CHANGELOG_CHARS).collect(); |
| 158 | format!( |
| 159 | "{truncated}\n\ |
| 160 | \n\ |
| 161 | [... {} characters omitted from the bundled Codewhale changelog]", |
| 162 | total_chars - MAX_INLINE_CHANGELOG_CHARS |
| 163 | ) |
| 164 | } |
| 165 | |
| 166 | /// Extract the latest version section from CHANGELOG.md content. |
| 167 | /// |
| 168 | /// Looks for the first `## [version] - date` heading and returns all lines |
| 169 | /// from that heading up to the next `## [` heading (or end of file). |
| 170 | /// Leading and trailing whitespace is trimmed. |
| 171 | /// |
| 172 | /// Skips empty sections (e.g. `## [Unreleased]` with no content) to find |
| 173 | /// the first section that actually has content. |
| 174 | pub fn extract_latest_changelog_section(content: &str) -> Option<String> { |
| 175 | let lines: Vec<&str> = content.lines().collect(); |
| 176 | |
| 177 | // Find the first `## [` heading index |
| 178 | let first_idx = { |
| 179 | let mut idx = None; |
| 180 | for (i, line) in lines.iter().enumerate() { |
| 181 | if line.trim().starts_with("## [") { |
| 182 | idx = Some(i); |
| 183 | break; |
| 184 | } |
| 185 | } |
| 186 | idx? |
| 187 | }; |
| 188 | |
| 189 | // Starting from `first_idx`, walk through headings until we find a |
| 190 | // section with non-empty content. |
| 191 | let mut pos = first_idx; |
| 192 | loop { |
| 193 | let end = lines |
| 194 | .iter() |
| 195 | .enumerate() |
| 196 | .skip(pos + 1) |
| 197 | .find(|(_, line)| line.trim().starts_with("## [")) |
| 198 | .map_or(lines.len(), |(i, _)| i); |
| 199 | |
| 200 | if section_has_body_content(&lines[pos + 1..end]) { |
| 201 | return Some(lines[pos..end].join("\n").trim().to_string()); |
| 202 | } |
| 203 | |
| 204 | // Empty section — try the next heading (if any) |
| 205 | if end >= lines.len() { |
| 206 | return None; |
| 207 | } |
| 208 | pos = end; |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | /// Extract a specific version section from CHANGELOG.md content. |
| 213 | /// |
| 214 | /// Looks for `## [<version>]` or `## [<version> - date]` and returns all |
| 215 | /// lines from that heading up to the next `## [` heading (or end of file). |
| 216 | pub fn extract_changelog_section_by_version(content: &str, version: &str) -> Option<String> { |
| 217 | let lines: Vec<&str> = content.lines().collect(); |
| 218 | let mut start_idx: Option<usize> = None; |
| 219 | |
| 220 | for (i, line) in lines.iter().enumerate() { |
| 221 | let trimmed = line.trim(); |
| 222 | if trimmed.starts_with("## [") { |
| 223 | // Check if this heading matches the requested version. |
| 224 | // Format: `## [0.8.32] - 2026-05-12` or `## [0.8.32]` |
| 225 | let bracket_end = trimmed.find(']')?; |
| 226 | let heading_ver = &trimmed[4..bracket_end]; // skip "## [" |
| 227 | if heading_ver == version { |
| 228 | start_idx = Some(i); |
| 229 | break; |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | let start = start_idx?; |
| 235 | |
| 236 | let end = lines |
| 237 | .iter() |
| 238 | .enumerate() |
| 239 | .skip(start + 1) |
| 240 | .find(|(_, line)| line.trim().starts_with("## [")) |
| 241 | .map_or(lines.len(), |(i, _)| i); |
| 242 | |
| 243 | if !section_has_body_content(&lines[start + 1..end]) { |
| 244 | return None; |
| 245 | } |
| 246 | |
| 247 | Some(lines[start..end].join("\n").trim().to_string()) |
| 248 | } |
| 249 | |
| 250 | /// Extract the version number of the section immediately preceding the latest |
| 251 | /// non-empty section in the changelog. |
| 252 | /// |
| 253 | /// Walks past empty sections (e.g. `## [Unreleased]`) the same way |
| 254 | /// [`extract_latest_changelog_section`] does, then returns the version from |
| 255 | /// the next `## [version]` heading after the first contentful section. |
| 256 | pub fn extract_previous_version_number(content: &str) -> Option<String> { |
| 257 | let lines: Vec<&str> = content.lines().collect(); |
| 258 | let first_idx = lines.iter().position(|l| l.trim().starts_with("## ["))?; |
| 259 | |
| 260 | let mut pos = first_idx; |
| 261 | loop { |
| 262 | let end = lines |
| 263 | .iter() |
| 264 | .enumerate() |
| 265 | .skip(pos + 1) |
| 266 | .find(|(_, l)| l.trim().starts_with("## [")) |
| 267 | .map_or(lines.len(), |(i, _)| i); |
| 268 | |
| 269 | if section_has_body_content(&lines[pos + 1..end]) { |
| 270 | // Found the latest contentful section heading at `pos`. |
| 271 | return next_contentful_version_after(&lines, end); |
| 272 | } |
| 273 | |
| 274 | if end >= lines.len() { |
| 275 | return None; |
| 276 | } |
| 277 | pos = end; |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 282 | pub struct ChangelogEntryCounts { |
| 283 | pub features: usize, |
| 284 | pub fixes: usize, |
| 285 | pub other: usize, |
| 286 | } |
| 287 | |
| 288 | pub fn count_changelog_entries(section: &str) -> ChangelogEntryCounts { |
| 289 | const UNCOUNTED: [&str; 5] = [ |
| 290 | "contributors", |
| 291 | "thanks", |
| 292 | "community", |
| 293 | "known ", |
| 294 | "retroactive", |
| 295 | ]; |
| 296 | let mut counts = ChangelogEntryCounts::default(); |
| 297 | let mut slot: Option<usize> = None; |
| 298 | for line in section.lines() { |
| 299 | if let Some(heading) = line.strip_prefix("### ") { |
| 300 | let heading = heading.trim().to_ascii_lowercase(); |
| 301 | slot = if heading.starts_with("added") || heading.starts_with("new") { |
| 302 | Some(0) |
| 303 | } else if heading.starts_with("fixed") |
| 304 | || heading.starts_with("security") |
| 305 | || heading.contains("fixes") |
| 306 | { |
| 307 | Some(1) |
| 308 | } else if UNCOUNTED.iter().any(|prefix| heading.starts_with(prefix)) { |
| 309 | None |
| 310 | } else { |
| 311 | Some(2) |
| 312 | }; |
| 313 | } else if line.starts_with("## ") { |
| 314 | slot = None; |
| 315 | } else if line.starts_with("- ") { |
| 316 | match slot { |
| 317 | Some(0) => counts.features += 1, |
| 318 | Some(1) => counts.fixes += 1, |
| 319 | Some(_) => counts.other += 1, |
| 320 | None => {} |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | counts |
| 325 | } |
| 326 | |
| 327 | pub fn section_has_body_content(lines: &[&str]) -> bool { |
| 328 | lines.iter().any(|line| !line.trim().is_empty()) |
| 329 | } |
| 330 | |
| 331 | pub fn previous_version_hint(content: &str, version: Option<&str>) -> Option<String> { |
| 332 | match version.map(str::trim).filter(|v| !v.is_empty()) { |
| 333 | Some(version) => extract_previous_version_number_after_version(content, version), |
| 334 | None => extract_previous_version_number(content), |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | pub fn extract_previous_version_number_after_version( |
| 339 | content: &str, |
| 340 | version: &str, |
| 341 | ) -> Option<String> { |
| 342 | let lines: Vec<&str> = content.lines().collect(); |
| 343 | let current_start = lines.iter().position(|line| { |
| 344 | let trimmed = line.trim(); |
| 345 | trimmed |
| 346 | .strip_prefix("## [") |
| 347 | .and_then(|rest| rest.split_once(']')) |
| 348 | .is_some_and(|(heading_ver, _)| heading_ver == version) |
| 349 | })?; |
| 350 | |
| 351 | let current_end = lines |
| 352 | .iter() |
| 353 | .enumerate() |
| 354 | .skip(current_start + 1) |
| 355 | .find(|(_, line)| line.trim().starts_with("## [")) |
| 356 | .map_or(lines.len(), |(i, _)| i); |
| 357 | |
| 358 | next_contentful_version_after(&lines, current_end) |
| 359 | } |
| 360 | |
| 361 | pub fn next_contentful_version_after(lines: &[&str], mut pos: usize) -> Option<String> { |
| 362 | while pos < lines.len() { |
| 363 | let heading = lines[pos].trim(); |
| 364 | if !heading.starts_with("## [") { |
| 365 | pos += 1; |
| 366 | continue; |
| 367 | } |
| 368 | |
| 369 | let end = lines |
| 370 | .iter() |
| 371 | .enumerate() |
| 372 | .skip(pos + 1) |
| 373 | .find(|(_, line)| line.trim().starts_with("## [")) |
| 374 | .map_or(lines.len(), |(i, _)| i); |
| 375 | |
| 376 | if section_has_body_content(&lines[pos + 1..end]) { |
| 377 | let bracket_end = heading.find(']')?; |
| 378 | return Some(heading[4..bracket_end].to_string()); |
| 379 | } |
| 380 | |
| 381 | pos = end; |
| 382 | } |
| 383 | |
| 384 | None |
| 385 | } |
| 386 | |
| 387 | #[cfg(test)] |
| 388 | mod tests { |
| 389 | use super::*; |
| 390 | |
| 391 | #[test] |
| 392 | fn inline_changelog_section_uses_char_count_for_threshold_and_omission() { |
| 393 | let within_char_budget = format!("{}{}", "a".repeat(4080), "中".repeat(10)); |
| 394 | assert!(within_char_budget.len() > MAX_INLINE_CHANGELOG_CHARS); |
| 395 | assert_eq!( |
| 396 | inline_changelog_section(&within_char_budget), |
| 397 | within_char_budget |
| 398 | ); |
| 399 | |
| 400 | let over_char_budget = "中".repeat(4200); |
| 401 | let output = inline_changelog_section(&over_char_budget); |
| 402 | assert!(output.starts_with(&"中".repeat(MAX_INLINE_CHANGELOG_CHARS))); |
| 403 | assert!( |
| 404 | output.ends_with("[... 104 characters omitted from the bundled Codewhale changelog]"), |
| 405 | "unexpected omission notice: {output}" |
| 406 | ); |
| 407 | } |
| 408 | } |
| 409 |