diff --git a/src/worktree_manager.rs b/src/worktree_manager.rs index 643aae7..534aaac 100644 --- a/src/worktree_manager.rs +++ b/src/worktree_manager.rs @@ -76,6 +76,19 @@ pub fn ensure_worktrees_in_gitignore(repo_path: &Path, worktree_dir: &Path) -> R if content.lines().any(|line| line.trim() == pattern) { return Ok(()); } + + let mut file = OpenOptions::new() + .append(true) + .open(&gitignore_path) + .context("Failed to open .gitignore")?; + + if !content.is_empty() && !content.ends_with('\n') { + file.write_all(b"\n") + .context("Failed to write newline to .gitignore")?; + } + + writeln!(file, "{}", pattern).context("Failed to write to .gitignore")?; + return Ok(()); } let mut file = OpenOptions::new() diff --git a/tests/which_test.rs b/tests/which_test.rs index ad84d23..41db31e 100644 --- a/tests/which_test.rs +++ b/tests/which_test.rs @@ -119,6 +119,22 @@ fn test_ensure_worktrees_in_gitignore_appends_to_existing() { assert!(content.contains(".worktrees")); } +#[test] +fn test_ensure_worktrees_in_gitignore_adds_newline_when_missing() { + use wt::worktree_manager::ensure_worktrees_in_gitignore; + + let repo = setup_git_repo(); + let gitignore_path = repo.path().join(".gitignore"); + let worktree_dir = repo.path().join(".worktrees"); + + fs::write(&gitignore_path, "node_modules").unwrap(); + + ensure_worktrees_in_gitignore(repo.path(), &worktree_dir).unwrap(); + + let content = fs::read_to_string(&gitignore_path).unwrap(); + assert_eq!(content, "node_modules\n.worktrees\n"); +} + #[test] fn test_ensure_worktrees_in_gitignore_idempotent() { use wt::worktree_manager::ensure_worktrees_in_gitignore;