(7ac39e3) Fix byte-slice panics in id shortening and date formatting

Three places sliced strings by byte offset on values that come from a
filename or a file field, neither of which is validated.

The disambiguation list took &short_id[..7], so two tickets whose names
were shorter than that aborted the process while printing the options.
collect_ticket_items guarded on length but still cut at byte 7, so a
multibyte character straddling the cut panicked. format_created_at read
four fixed offsets after a length check that a multibyte value passes.

Add short_id, which counts characters, and use it in both display paths.
Parse the timestamp with chrono instead of slicing, dropping the column
when the value will not parse. The format string it writes and the one it
reads are now the same constant, so they cannot drift.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-08-20 13:56:10 +02:00
co-authored by Claude Opus 5
parent 8ff64614fc
commit c675da1d2a
4 changed files with 173 additions and 23 deletions
+2 -2
View File
@@ -174,7 +174,7 @@ pub fn cmd_add(
},
due.as_deref().unwrap_or("_Not set_"),
owner.as_deref().unwrap_or("_Not set_"),
Local::now().format("%Y-%m-%d %H:%M:%S"),
Local::now().format(TIMESTAMP_FORMAT),
);
body.push('\n');
@@ -390,7 +390,7 @@ pub fn cmd_comment(
",
body,
author,
Local::now().format("%Y-%m-%d %H:%M:%S")
Local::now().format(TIMESTAMP_FORMAT)
);
fs::write(&filepath, comment_content)?;
+79 -21
View File
@@ -1,8 +1,13 @@
use anyhow::{Result, anyhow};
use chrono::NaiveDateTime;
use std::fs;
use std::io::IsTerminal;
use std::path::Path;
/// How timestamps are written into tickets and comments, and therefore how they
/// are read back. Shared so the writer and the reader cannot drift apart.
pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
pub fn should_use_colors() -> bool {
std::io::stdout().is_terminal()
}
@@ -45,6 +50,26 @@ pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
))
}
/// Width of the abbreviated id shown by `ls` and by the disambiguation list.
pub const SHORT_ID_WIDTH: usize = 7;
/// The leading characters of `text`, counted in characters rather than bytes.
///
/// Byte slicing panics twice over here: on text shorter than the width, and on a
/// multibyte character straddling the cut. Both reach this code from a filename,
/// which nothing validates.
pub fn truncate_chars(text: &str, width: usize) -> &str {
match text.char_indices().nth(width) {
Some((byte, _)) => &text[..byte],
None => text,
}
}
/// A ticket id abbreviated for display.
pub fn short_id(id: &str) -> &str {
truncate_chars(id, SHORT_ID_WIDTH)
}
pub fn slug(title: &str) -> String {
title
.to_lowercase()
@@ -122,12 +147,11 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
if matches.len() > 1 {
println!("Multiple tickets found matching '{}':", search);
for (i, (status, title, _, short_id)) in matches.iter().enumerate() {
let display_id = &short_id[..7];
for (i, (status, title, _, id)) in matches.iter().enumerate() {
println!(
" {}. ({}) {} [{}]",
i + 1,
color_text(display_id, "red"),
color_text(short_id(id), "red"),
title,
color_text(status, "orange"),
);
@@ -379,20 +403,16 @@ pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Resu
Ok(updated)
}
// Format created_at for display with proper spacing and formatting.
// Format created_at for display: "YYYY-MM-DD HH:MM:SS" becomes "YY-MM-DD:HH".
//
// Parsed rather than sliced by byte offset: the value comes from a file nothing
// validates, and the old offsets panicked on any multibyte character before them.
// Anything unparseable yields an empty string, which drops the column.
pub fn format_created_at(created_at: &str) -> String {
if created_at == "_Not set_" || created_at.is_empty() {
return String::new();
match NaiveDateTime::parse_from_str(created_at, TIMESTAMP_FORMAT) {
Ok(created_at) => created_at.format("%y-%m-%d:%H").to_string(),
Err(_) => String::new(),
}
if created_at.len() < 16 {
return created_at.to_string();
}
// Parse "YYYY-MM-DD HH:MM:SS" -> "YY-MM-DD:HH"
let year = &created_at[2..4];
let month = &created_at[5..7];
let day = &created_at[8..10];
let hour = &created_at[11..13];
format!("{}-{}-{}:{}", year, month, day, hour)
}
pub fn status_dirs() -> Vec<&'static str> {
@@ -434,18 +454,56 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
let owner = parse_ticket_field(&content, "Owner");
let due = parse_ticket_field(&content, "Due");
let filename = e.path().file_stem()?.to_string_lossy().to_string();
let uuid_short = if filename.len() > 7 {
&filename[..7]
} else {
&filename
};
let created_at = parse_ticket_field(&content, "Created At");
let short_date = format_created_at(&created_at);
Some((title, owner, due, uuid_short.to_string(), short_date))
Some((
title,
owner,
due,
short_id(&filename).to_string(),
short_date,
))
})
.collect();
items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));
Ok(items)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_id_shortens_a_full_uuid() {
assert_eq!(short_id("c230d2c6-d78a-44a5-8f5f-88fb28f84493"), "c230d2c");
}
#[test]
fn short_id_leaves_anything_shorter_alone() {
assert_eq!(short_id("abc"), "abc");
assert_eq!(short_id(""), "");
assert_eq!(short_id("abcdefg"), "abcdefg");
}
/// The cut used to land inside a character and panic.
#[test]
fn short_id_counts_characters_not_bytes() {
assert_eq!(short_id("émigré-ticket"), "émigré-");
assert_eq!(short_id("日本語"), "日本語");
}
#[test]
fn created_at_is_shortened_for_display() {
assert_eq!(format_created_at("2026-08-20 13:06:34"), "26-08-20:13");
}
/// Every one of these reached the old byte offsets from an unvalidated file.
#[test]
fn unparseable_created_at_drops_the_column() {
for value in ["_Not set_", "", "2026-08-20", "日本語日本語日本語", "not a date at all"] {
assert_eq!(format_created_at(value), "", "for {value:?}");
}
}
}
+42
View File
@@ -174,3 +174,45 @@ fn ls_displays_owner_and_due() {
assert!(stdout.contains("alice"));
assert!(stdout.contains("2026-12-31"));
}
/// Both the abbreviated id and the created-at column used to slice by byte
/// offset, so either a short name or a multibyte character panicked.
#[test]
fn ls_handles_short_and_non_ascii_filenames() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
for filename in ["ab.md", "émigré-ticket.md", "日本語.md"] {
fs::write(
worklane.join("backlog").join(filename),
"# Odd Name\n\n## Metadata\n\n- **Owner**: alice\n- **Status**: backlog\n",
)
.unwrap();
}
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("ls").arg("backlog").assert().success();
let stdout = get_stdout(&mut cmd);
assert_eq!(stdout.matches("Odd Name").count(), 3);
}
#[test]
fn ls_survives_a_malformed_created_at() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
fs::write(
worklane.join("backlog").join("00000000-0000-0000-0000-000000000009_bad-date.md"),
"# Bad Date\n\n## Metadata\n\n- **Created At**: 日本語日本語日本語\n- **Status**: backlog\n",
)
.unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("ls").arg("backlog").assert().success();
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Bad Date"));
// Unparseable, so the timestamp column is dropped rather than printed raw
assert!(!stdout.contains("日本語"));
}
+50
View File
@@ -265,6 +265,56 @@ fn show_asks_for_disambiguation_when_multiple_matches() {
assert!(stdout.contains("Use the displayed ID"));
}
/// Filenames shorter than the displayed id width used to panic while printing
/// the disambiguation list.
#[test]
fn show_disambiguates_tickets_with_short_filenames() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
fs::write(
worklane.join("backlog").join("abc.md"),
"# Short One\n\n## Metadata\n\n- **ID**: 1234\n",
)
.unwrap();
fs::write(
worklane.join("backlog").join("xy.md"),
"# Short Two\n\n## Metadata\n\n- **ID**: 5678\n",
)
.unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("short");
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Multiple tickets found"));
assert!(stdout.contains("Short One"));
assert!(stdout.contains("Short Two"));
}
/// A multibyte character straddling the cut used to panic.
#[test]
fn show_disambiguates_tickets_with_non_ascii_filenames() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
for (filename, title) in [("émigré-un.md", "Accented One"), ("日本語-二.md", "Accented Two")] {
fs::write(
worklane.join("backlog").join(filename),
format!("# {}\n\n## Metadata\n\n- **ID**: 1234\n", title),
)
.unwrap();
}
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("accented");
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Multiple tickets found"));
assert!(stdout.contains("Accented One"));
assert!(stdout.contains("Accented Two"));
}
#[test]
fn show_searches_across_all_statuses() {
let temp = TempDir::new().unwrap();