diff --git a/Cargo.lock b/Cargo.lock index 6676e35..5774085 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1029,7 +1029,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 1ba9b07..b442602 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.1.0" +version = "0.1.1" edition = "2024" [dependencies] diff --git a/src/handlers.rs b/src/handlers.rs index 685f077..432736a 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1,6 +1,7 @@ use anyhow::{Result, anyhow}; use chrono::Local; use std::fs; +use std::io::Write; use std::path::Path; use crate::util::*; @@ -234,6 +235,40 @@ fn read_comments(comments_dir: &Path) -> Result Result { + for attempt in 0..100 { + let filename = match attempt { + 0 => format!("{}.md", stem), + n => format!("{}_{:02}.md", stem, n), + }; + + match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(comments_dir.join(&filename)) + { + Ok(mut file) => { + file.write_all(content.as_bytes())?; + return Ok(filename); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.into()), + } + } + + Err(anyhow!( + "No free comment filename for '{}' in {}", + stem, + comments_dir.display() + )) +} + pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> { let (_status, title, content) = resolve_ticket(search, worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); @@ -351,6 +386,39 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) - Ok(()) } +#[cfg(test)] +mod tests { + use super::*; + + /// The collision path cannot be provoked from the CLI, since two processes + /// will not share a microsecond, but it is the whole point of the guard. + #[test] + fn a_colliding_stem_takes_the_next_name_and_keeps_the_first() { + let dir = std::env::temp_dir().join(format!("worklane-test-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&dir).unwrap(); + + let first = write_new_comment(&dir, "20260820_143012_123456", "first").unwrap(); + let second = write_new_comment(&dir, "20260820_143012_123456", "second").unwrap(); + let third = write_new_comment(&dir, "20260820_143012_123456", "third").unwrap(); + + assert_eq!(first, "20260820_143012_123456.md"); + assert_eq!(second, "20260820_143012_123456_01.md"); + assert_eq!(third, "20260820_143012_123456_02.md"); + + // Nothing was truncated on the way through + assert_eq!(fs::read_to_string(dir.join(&first)).unwrap(), "first"); + assert_eq!(fs::read_to_string(dir.join(&second)).unwrap(), "second"); + assert_eq!(fs::read_to_string(dir.join(&third)).unwrap(), "third"); + + // read_comments sorts on the stem, so the names must sort in write order + let mut names = vec![second.clone(), third.clone(), first.clone()]; + names.sort(); + assert_eq!(names, vec![first, second, third]); + + fs::remove_dir_all(&dir).unwrap(); + } +} + pub fn cmd_comment( ticket_id: &str, body: &str, @@ -372,9 +440,7 @@ pub fn cmd_comment( let comments_dir = worklane_dir.join("comments").join(&ticket_uuid); fs::create_dir_all(&comments_dir)?; - let timestamp = Local::now().format("%Y%m%d_%H%M%S"); - let filename = format!("{}.md", timestamp); - let filepath = comments_dir.join(&filename); + let stem = Local::now().format(COMMENT_FILE_FORMAT).to_string(); let author = match owner { Some(o) => o.clone(), @@ -393,7 +459,7 @@ pub fn cmd_comment( Local::now().format(TIMESTAMP_FORMAT) ); - fs::write(&filepath, comment_content)?; + let filename = write_new_comment(&comments_dir, &stem, &comment_content)?; println!("Comment added to '{}' ({})", title, filename); Ok(()) diff --git a/src/util.rs b/src/util.rs index 980b5bb..8902b34 100644 --- a/src/util.rs +++ b/src/util.rs @@ -8,6 +8,13 @@ use std::path::Path; /// are read back. Shared so the writer and the reader cannot drift apart. pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S"; +/// How a comment filename is stamped. +/// +/// Microseconds, not seconds: at second resolution two comments in the same +/// second produced the same name and the second silently truncated the first. +/// Fixed width, so the lexicographic sort in `read_comments` stays chronological. +pub const COMMENT_FILE_FORMAT: &str = "%Y%m%d_%H%M%S_%6f"; + pub fn should_use_colors() -> bool { std::io::stdout().is_terminal() } diff --git a/tests/cmd_comment.rs b/tests/cmd_comment.rs index 81562ef..cc61096 100644 --- a/tests/cmd_comment.rs +++ b/tests/cmd_comment.rs @@ -212,3 +212,41 @@ fn comment_falls_back_to_git_user_when_owner_omitted() { let content = fs::read_to_string(files[0].path()).unwrap(); assert!(content.contains("**Author**")); } + +/// Second-resolution filenames meant the second of two quick comments +/// truncated the first. +#[test] +fn comments_added_back_to_back_are_both_kept() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + let uuid = create_ticket(&worklane, "backlog", "Rapid Fire"); + + for body in ["first comment", "second comment", "third comment"] { + Command::cargo_bin(BIN_NAME) + .unwrap() + .current_dir(&temp.path()) + .arg("comment") + .args([&uuid, body]) + .assert() + .success(); + } + + let comments_dir = worklane.join("comments").join(&uuid); + let files: Vec<_> = fs::read_dir(&comments_dir) + .unwrap() + .filter_map(|e| e.ok()) + .collect(); + assert_eq!(files.len(), 3, "a comment was overwritten"); + + // And show has to render them in the order they were added + let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); + cmd.current_dir(&temp.path()).arg("show").arg(&uuid); + let assert = cmd.assert().success(); + let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + + let first = stdout.find("first comment").expect("first comment missing"); + let second = stdout.find("second comment").expect("second comment missing"); + let third = stdout.find("third comment").expect("third comment missing"); + assert!(first < second && second < third, "comments out of order"); +}