Files
worklane/tests/cmd_mv.rs
T
Ansho ReiandClaude Opus 5 e20396ce6b (322150c) Make mv crash-safe by writing before renaming, and bump to 0.3.3
cmd_mv renamed the ticket into its new directory and only then wrote the updated
content, so a write that failed left the ticket in the target directory still
claiming the old status. Reproduced with a read-only ticket file: the move
reported a bare "Permission denied" and left the file in committed/ carrying
"Status: backlog".

move_ticket_file now stages the content in a temp file, renames it over the
source, and only then renames the file into the target directory. Two atomic
steps, so a partial write is discarded and the original is untouched. The other
obvious order, writing to the target and deleting the source afterwards, was
rejected because it has the ticket in two directories at once.

The worst case left is a ticket still in its old directory with a Status one
move ahead, which the next mv corrects since the directory is what decides the
current status. Tested, including the retry.

The temp file is staged under .worklane/ rather than beside the ticket, so a
leftover from a hard kill is invisible to ticket lookup and to the listing
instead of appearing as a stray untitled ticket. IO errors now name the ticket
and the path rather than propagating bare.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 23:12:17 +02:00

605 lines
17 KiB
Rust

use assert_cmd::Command;
use assert_fs::TempDir;
use assert_fs::fixture::{PathChild, PathCreateDir};
use std::fs;
use std::path::PathBuf;
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
fn setup_worklane(temp: &TempDir) -> PathBuf {
let worklane = temp.child(".worklane");
worklane.create_dir_all().unwrap();
for dir in ["backlog", "committed", "reviewing", "done"] {
worklane.child(dir).create_dir_all().unwrap();
}
worklane.path().to_path_buf()
}
fn create_ticket(
worklane_dir: &PathBuf,
status: &str,
title: &str,
description: &str,
id: &str,
owner: &str,
due: &str,
tags: &str,
) -> String {
let slug = title
.to_lowercase()
.chars()
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
.map(|c| if c == ' ' { '-' } else { c })
.collect::<String>();
let filename = format!("{}_{}.md", id, slug);
let ticket_body = format!(
"# {}\n\
\n\
## Description\n\
{}\n\
\n\
## Acceptance Criteria\n\
- [ ] test\n\
\n\
## Implementation Plan\n\
- test\n\
\n\
## Metadata\n\
\n\
- **ID**: {}\n\
- **Tags**: {}\n\
- **Due**: {}\n\
- **Owner**: {}\n\
- **Status**: {}\n\
",
title, description, id, tags, due, owner, status
);
let path = worklane_dir.join(status).join(&filename);
fs::write(&path, ticket_body).unwrap();
filename
}
fn get_stdout(cmd: &mut Command) -> String {
let assert = cmd.assert();
String::from_utf8(assert.get_output().stdout.clone()).unwrap()
}
fn get_stderr(cmd: &mut Command) -> String {
let assert = cmd.assert();
String::from_utf8(assert.get_output().stderr.clone()).unwrap()
}
#[test]
fn mv_forwards_from_backlog_to_committed() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&worklane,
"backlog",
"Task One",
"Move this ticket.",
id,
"alice",
"2026-12-31",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("committed");
let assert = cmd.assert();
let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
assert.success();
assert!(stdout.contains("Task One"));
assert!(stdout.contains("backlog"));
assert!(stdout.contains("committed"));
// Verify file moved
assert!(!worklane.join("backlog").join(&filename).exists());
assert!(worklane.join("committed").join(&filename).exists());
// Verify status updated
let content = fs::read_to_string(worklane.join("committed").join(&filename)).unwrap();
assert!(content.contains("- **Status**: committed"));
// No stray blank line inserted after the rewritten field
assert!(content.ends_with("- **Status**: committed\n"));
}
#[test]
fn mv_blocks_backward_move() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
create_ticket(
&worklane,
"committed",
"Committed Task",
"Should stay committed.",
id,
"bob",
"2026-11-15",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("backlog")
.assert()
.failure();
let stderr = get_stderr(&mut cmd);
assert!(stderr.contains("Cannot move backward"));
}
#[test]
fn mv_allows_backward_move_with_force() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&worklane,
"committed",
"Backward Move",
"Force backward.",
id,
"charlie",
"2026-10-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("backlog")
.arg("-f");
let assert = cmd.assert();
let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
assert.success();
assert!(stdout.contains("Backward Move"));
assert!(stdout.contains("backlog"));
assert!(worklane.join("backlog").join(&filename).exists());
}
#[test]
fn mv_blocks_nonsequential_forward_move() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
create_ticket(
&worklane,
"backlog",
"Jump Task",
"Should not skip.",
id,
"dave",
"2026-09-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("done")
.assert()
.failure();
let stderr = get_stderr(&mut cmd);
assert!(stderr.contains("one stage forward"));
}
#[test]
fn mv_allows_skipping_stages_with_force() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&worklane,
"backlog",
"Skip Task",
"Force jump.",
id,
"eve",
"2026-08-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("done")
.arg("-f")
.assert()
.success();
assert!(worklane.join("done").join(&filename).exists());
let content = fs::read_to_string(worklane.join("done").join(&filename)).unwrap();
assert!(content.contains("- **Status**: done"));
}
#[test]
fn mv_ignores_already_in_same_status() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&worklane,
"reviewing",
"Same Status",
"Already there.",
id,
"frank",
"2026-07-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("reviewing")
.assert()
.success();
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("already in"));
assert!(worklane.join("reviewing").join(&filename).exists());
}
#[test]
fn mv_rejects_invalid_status() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let _filename = create_ticket(
&worklane,
"backlog",
"Invalid Target",
"Bad status.",
id,
"grace",
"2026-06-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("invalid")
.assert()
.failure();
let stderr = get_stderr(&mut cmd);
assert!(stderr.contains("Invalid target status"));
}
#[test]
fn mv_uses_ticket_id_for_resolution() {
let temp = TempDir::new().unwrap();
let wl = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&wl,
"backlog",
"ID Resolution",
"Use ID to find.",
id,
"hank",
"2026-05-01",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("committed");
let assert = cmd.assert();
let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
assert.success();
assert!(stdout.contains("ID Resolution"));
assert!(wl.join("committed").join(&filename).exists());
}
#[test]
fn mv_keeps_status_in_sync_across_consecutive_moves() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let id = "abc123def456789012345678901234567890";
let filename = create_ticket(
&worklane,
"backlog",
"Two Hop",
"Moved twice.",
id,
"ida",
"2026-04-01",
"test",
);
for target in ["committed", "reviewing"] {
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg(target)
.assert()
.success();
}
assert!(worklane.join("reviewing").join(&filename).exists());
// The second move must update the field too, not silently skip it
let content = fs::read_to_string(worklane.join("reviewing").join(&filename)).unwrap();
assert!(content.contains("- **Status**: reviewing"));
assert!(!content.contains("-Status"));
assert!(!content.contains("committed"));
}
#[test]
fn mv_repairs_legacy_status_field() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = "abc123def456789012345678901234567890_legacy.md";
let path = worklane.join("committed").join(filename);
fs::write(
&path,
"# Legacy Ticket\n\
\n\
## Metadata\n\
\n\
- **ID**: abc123def456789012345678901234567890\n\
- **-Status**: committed\n",
)
.unwrap();
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("reviewing")
.assert()
.success();
let content = fs::read_to_string(worklane.join("reviewing").join(filename)).unwrap();
assert!(content.contains("- **Status**: reviewing"));
assert!(!content.contains("-Status"));
}
#[test]
fn mv_fails_when_status_field_is_missing() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = "abc123def456789012345678901234567890_no-status.md";
let path = worklane.join("backlog").join(filename);
fs::write(&path, "# No Status\n\n## Metadata\n\n- **Owner**: jack\n").unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.arg("mv")
.arg("abc123def4567")
.arg("--status")
.arg("committed")
.assert()
.failure();
let stderr = get_stderr(&mut cmd);
assert!(stderr.contains("No Status"));
assert!(stderr.contains("has no Status field"));
// The ticket must not be half-moved
assert!(worklane.join("backlog").join(filename).exists());
assert!(!worklane.join("committed").join(filename).exists());
}
use std::os::unix::fs::PermissionsExt;
fn chmod(path: &std::path::Path, mode: u32) {
let mut perms = fs::metadata(path).unwrap().permissions();
perms.set_mode(mode);
fs::set_permissions(path, perms).unwrap();
}
fn md_files(dir: &std::path::Path) -> Vec<String> {
match fs::read_dir(dir) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| name.ends_with(".md"))
.collect(),
Err(_) => vec![],
}
}
/// Nothing is staged in a status directory, so nothing can be left behind that the
/// listing would read as a ticket.
fn stray_files(worklane: &std::path::Path) -> Vec<String> {
let mut stray: Vec<String> = fs::read_dir(worklane)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| !["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str()))
.collect();
for dir in ["backlog", "committed", "reviewing", "done"] {
stray.extend(
fs::read_dir(worklane.join(dir))
.into_iter()
.flatten()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| !name.ends_with(".md")),
);
}
stray
}
/// The bug this fixes. The old order renamed first and wrote second, so a write
/// that failed left the ticket in its new directory still claiming the old status.
/// A read-only ticket file is the cheapest way to make the write fail.
#[test]
fn mv_never_leaves_stale_content_in_the_target_directory() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_ticket(
&worklane,
"backlog",
"Read Only",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let source = worklane.join("backlog").join(&filename);
chmod(&source, 0o444);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
// Wherever it ended up, its Status must agree with the directory it is in
let moved = worklane.join("committed").join(&filename);
assert!(moved.exists(), "ticket did not move");
let content = fs::read_to_string(&moved).unwrap();
assert!(
content.contains("- **Status**: committed"),
"stale status: {content:?}"
);
assert!(!content.contains("- **Status**: backlog"), "{content:?}");
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
assert_eq!(stray_files(&worklane), Vec::<String>::new());
}
/// The other criterion: one directory or the other, never both. An unwritable
/// target directory fails the move at the last step, which is the step that would
/// have to be reordered to break this.
#[test]
fn mv_leaves_the_ticket_in_one_place_when_the_move_fails() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_ticket(
&worklane,
"backlog",
"Blocked Move",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let target = worklane.join("committed");
chmod(&target, 0o555);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
let assert = cmd
.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.failure();
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
// Named, not a bare io error
assert!(stderr.contains("Blocked Move"), "{stderr}");
assert_eq!(
md_files(&worklane.join("backlog")),
vec![filename.clone()],
"the ticket left its own directory"
);
assert_eq!(md_files(&target).len(), 0, "the ticket is in both places");
assert_eq!(stray_files(&worklane), Vec::<String>::new());
// The documented worst case: still in its old directory, carrying a Status one
// move ahead because the content was written before the move was attempted.
let left = fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap();
assert!(left.contains("- **Status**: committed"), "{left:?}");
// And the state is recoverable, because the directory is what decides the
// current status, so a retry moves it rather than refusing.
chmod(&target, 0o755);
let mut retry = Command::cargo_bin(BIN_NAME).unwrap();
retry
.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
assert_eq!(md_files(&target), vec![filename]);
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
}
#[test]
fn mv_leaves_nothing_behind_on_success() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(
&worklane,
"backlog",
"Clean Move",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
assert_eq!(stray_files(&worklane), Vec::<String>::new());
}