package diff_test import ( "bytes" "os" "path/filepath" "testing" "git.sr.ht/~jcmuller/claude-plugins/internal/diff" "git.sr.ht/~jcmuller/claude-plugins/transcript" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNew_CreatesTempDir(t *testing.T) { t.Parallel() d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck info, err := os.Stat(d.Dir()) require.NoError(t, err) assert.True(t, info.IsDir()) assert.Equal(t, os.FileMode(0o700), info.Mode().Perm()) } func TestClose_RemovesTempDir(t *testing.T) { t.Parallel() d, err := diff.New() require.NoError(t, err) dir := d.Dir() require.NoError(t, d.Close()) _, err = os.Stat(dir) assert.True(t, os.IsNotExist(err)) } func TestMakeTemp_CreatesFileWith0600(t *testing.T) { t.Parallel() d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck path, err := d.MakeTemp(".go", "backup") require.NoError(t, err) assert.True(t, filepath.IsAbs(path)) info, err := os.Stat(path) require.NoError(t, err) assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) } func TestMakeTemp_PathInsideTempDir(t *testing.T) { t.Parallel() d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck path, err := d.MakeTemp(".rb", "display") require.NoError(t, err) assert.Contains(t, path, d.Dir()) } func TestBackup_CopiesFileContents(t *testing.T) { t.Parallel() src := filepath.Join(t.TempDir(), "original.go") require.NoError(t, os.WriteFile(src, []byte("package main\n"), 0o600)) d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck backup, err := d.Backup(src, ".go") require.NoError(t, err) got, err := os.ReadFile(backup) require.NoError(t, err) assert.Equal(t, "package main\n", string(got)) } func TestBackup_EmptyForNonExistentSource(t *testing.T) { t.Parallel() d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck backup, err := d.Backup("/nonexistent/path.go", ".go") require.NoError(t, err) info, err := os.Stat(backup) require.NoError(t, err) assert.Equal(t, int64(0), info.Size()) } func TestApplyWrite_CreatesFileWithContent(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "new.go") require.NoError(t, diff.ApplyWrite(filePath, "package main\n")) got, err := os.ReadFile(filePath) require.NoError(t, err) assert.Equal(t, "package main\n", string(got)) } func TestApplyWrite_CreatesParentDirs(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "sub", "dir", "file.go") require.NoError(t, diff.ApplyWrite(filePath, "content")) _, err := os.Stat(filePath) require.NoError(t, err) } func TestApplyEdit_ReplacesFirstOccurrence(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "file.go") original := "aaa bbb aaa" require.NoError(t, os.WriteFile(filePath, []byte(original), 0o600)) require.NoError(t, diff.ApplyEdit(filePath, "aaa", "ccc", false)) got, err := os.ReadFile(filePath) require.NoError(t, err) assert.Equal(t, "ccc bbb aaa", string(got)) } func TestApplyEdit_ReplaceAll(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "file.go") original := "aaa bbb aaa" require.NoError(t, os.WriteFile(filePath, []byte(original), 0o600)) require.NoError(t, diff.ApplyEdit(filePath, "aaa", "ccc", true)) got, err := os.ReadFile(filePath) require.NoError(t, err) assert.Equal(t, "ccc bbb ccc", string(got)) } func TestContentChanged_SameContent(t *testing.T) { t.Parallel() dir := t.TempDir() a := filepath.Join(dir, "a") b := filepath.Join(dir, "b") require.NoError(t, os.WriteFile(a, []byte("same"), 0o600)) require.NoError(t, os.WriteFile(b, []byte("same"), 0o600)) changed, err := diff.ContentChanged(a, b) require.NoError(t, err) assert.False(t, changed) } func TestContentChanged_DifferentContent(t *testing.T) { t.Parallel() dir := t.TempDir() a := filepath.Join(dir, "a") b := filepath.Join(dir, "b") require.NoError(t, os.WriteFile(a, []byte("original"), 0o600)) require.NoError(t, os.WriteFile(b, []byte("modified"), 0o600)) changed, err := diff.ContentChanged(a, b) require.NoError(t, err) assert.True(t, changed) } func TestRestoreOriginal_ExistingFile(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "file.go") original := []byte("original content") modified := []byte("modified content") require.NoError(t, os.WriteFile(filePath, original, 0o600)) d, err := diff.New() require.NoError(t, err) defer d.Close() //nolint:errcheck backup, err := d.Backup(filePath, ".go") require.NoError(t, err) // Simulate the hook modifying the file require.NoError(t, os.WriteFile(filePath, modified, 0o600)) require.NoError(t, diff.RestoreOriginal(filePath, backup, false)) got, err := os.ReadFile(filePath) require.NoError(t, err) assert.Equal(t, string(original), string(got)) } func TestFindEditLine_FirstLine(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("needle\nalpha\nbeta\n"), 0o600)) assert.Equal(t, 1, diff.FindEditLine(path, "needle")) } func TestFindEditLine_MiddleLine(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("alpha\nbeta\nneedle\ndelta\n"), 0o600)) assert.Equal(t, 3, diff.FindEditLine(path, "needle")) } func TestFindEditLine_MultilineOldStr(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("alpha\nfirst\nsecond\ndelta\n"), 0o600)) // Multi-line oldStr should match the start line of the block. assert.Equal(t, 2, diff.FindEditLine(path, "first\nsecond")) } func TestFindEditLine_NotFound_Returns1(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("alpha\nbeta\n"), 0o600)) assert.Equal(t, 1, diff.FindEditLine(path, "nowhere")) } func TestFindEditLine_EmptyOldStr_Returns1(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("alpha\n"), 0o600)) assert.Equal(t, 1, diff.FindEditLine(path, "")) } func TestFindEditLine_MissingFile_Returns1(t *testing.T) { t.Parallel() assert.Equal(t, 1, diff.FindEditLine("/nonexistent/path.go", "anything")) } func TestStripContextBlock_RemovesMarkedBlock(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := "package main\n\nfunc main() {}\n" block := "# " + transcript.BeginMarker + "\n" + "# [context] Adding main stub\n" + "# " + transcript.EndMarker appended := original + "\n" + block + "\n" require.NoError(t, os.WriteFile(path, []byte(appended), 0o600)) stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.True(t, stripped, "strip should report that a block was removed") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, original, string(got)) } func TestStripContextBlock_RoundTripPreservesBodyWithTrailingNewline(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("package main\n\nfunc main() {}\n") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.AppendContextBlock(path, block)) stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "round trip must be byte-identical; got %q", got) } func TestStripContextBlock_RoundTripPreservesBodyWithoutTrailingNewline(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("one line no newline") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.AppendContextBlock(path, block)) stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "round trip must be byte-identical; got %q", got) } // sentinelBlock returns body framed in begin/end marker comment lines, // matching what transcript.format produces for callers of AppendContextBlock. func sentinelBlock(body string) string { return "// " + transcript.BeginMarker + "\n" + body + "\n// " + transcript.EndMarker } func TestStripContextBlock_NonMatchingSuffixIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") // Contains a begin marker but not the exact bytes we expect as a suffix. // With exact-match strip this is safely a no-op rather than a data-loss // error path, which is what idempotency demands. contents := "package main\n\n# " + transcript.BeginMarker + "\n# lost\n" require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) block := "# " + transcript.BeginMarker + "\n# [context] something else\n# " + transcript.EndMarker stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.False(t, stripped, "non-matching suffix must be a no-op, not an error") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, contents, string(got), "file must be untouched when strip finds no match") } func TestStripContextBlock_EndMarkerCollisionLeavesFileAlone(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.md") contents := "# docs\n\nExample:\n\n```\n" + transcript.EndMarker + "\n```\n" require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) block := "# " + transcript.BeginMarker + "\n# [context] x\n# " + transcript.EndMarker stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.False(t, stripped, "end-marker inside a code block must not trigger a strip") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, contents, string(got)) } func TestStripContextBlock_NoMarkersIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") contents := "package main\n" require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) block := sentinelBlock("// [context] unrelated") stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.False(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, contents, string(got)) } func TestStripContextBlock_StripsBlockAfterExternalWhitespaceMutation(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.md") original := "# heading\n\nbody\n" block := "# " + transcript.BeginMarker + "\n" + "# [context] note\n" + "# " + transcript.EndMarker require.NoError(t, os.WriteFile(path, []byte(original+"\n"+block+"\n"), 0o600)) // Simulate an editor or file watcher modifying a block line (e.g., // trailing whitespace normalization). Exact-byte strip would silently // leave the block in place; sentinel-line strip must recover. raw, err := os.ReadFile(path) require.NoError(t, err) mutated := bytes.Replace( raw, []byte("# [context] note\n"), []byte("# [context] note \n"), 1, ) require.NoError(t, os.WriteFile(path, mutated, 0o600)) stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.True(t, stripped, "strip must succeed even after external mutation of block lines") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, original, string(got)) } func TestStripContextBlock_SecondCallIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("package main\n") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.AppendContextBlock(path, block)) // First strip succeeds. stripped, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.True(t, stripped) // Second strip on the already-cleaned file must be a safe no-op. stripped2, err := diff.StripContextBlock(path, block) require.NoError(t, err) assert.False(t, stripped2) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "body must be unchanged after two strips") } func TestPrependContextBlock_RoundTripPreservesBodyWithTrailingNewline(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("package main\n\nfunc main() {}\n") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.PrependContextBlock(path, block)) stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "round trip must be byte-identical; got %q", got) } func TestPrependContextBlock_RoundTripPreservesBodyWithoutTrailingNewline(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("one line no newline") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.PrependContextBlock(path, block)) stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "round trip must be byte-identical; got %q", got) } func TestPrependContextBlock_PlacesBlockAtTop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") require.NoError(t, os.WriteFile(path, []byte("package main\n"), 0o600)) require.NoError(t, diff.PrependContextBlock(path, sentinelBlock("// [context] hi"))) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.HasPrefix(got, []byte("// "+transcript.BeginMarker)), "file must start with begin marker line; got %q", got) } func TestStripContextBlockTop_RemovesLeadingBlock(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.md") original := "# heading\n\nbody\n" block := "# " + transcript.BeginMarker + "\n" + "# [context] note\n" + "# " + transcript.EndMarker contents := block + "\n\n" + original require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, original, string(got)) } func TestStripContextBlockTop_NoMarkersIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") contents := "package main\n" require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) block := sentinelBlock("// [context] unrelated") stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.False(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, contents, string(got)) } func TestStripContextBlockTop_PreservesContentBeforeBlock(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.md") // An external process (e.g., a Logseq watcher) may insert frontmatter // or other leading content between prepend and strip. Sentinel scan // must still find the block and remove only the sentinel-delimited // lines, preserving whatever appeared above it. block := "# " + transcript.BeginMarker + "\n" + "# [context] x\n" + "# " + transcript.EndMarker leader := "---\ntitle: Example\n---\n" body := "body text\n" // Simulate PrependContextBlock's output (block + "\n" + body) with an // externally-injected leader ahead of it. require.NoError(t, os.WriteFile(path, []byte(leader+block+"\n"+body), 0o600)) stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped) got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, leader+body, string(got)) } func TestStripContextBlockTop_NonMatchingPrefixIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") // Contains a begin marker at the top but not the exact bytes we expect. // Exact-match strip makes this a safe no-op rather than a data-loss // error path. contents := "# " + transcript.BeginMarker + "\n# [context] something else\npackage main\n" require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) block := "# " + transcript.BeginMarker + "\n# [context] expected\n# " + transcript.EndMarker stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.False(t, stripped, "non-matching prefix must be a no-op, not an error") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, contents, string(got), "file must be untouched when strip finds no match") } func TestStripContextBlockTop_StripsBlockAfterExternalWhitespaceMutation(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.md") original := "# heading\n\nbody\n" block := "# " + transcript.BeginMarker + "\n" + "# [context] note\n" + "# " + transcript.EndMarker require.NoError(t, os.WriteFile(path, []byte(block+"\n"+original), 0o600)) // Simulate an editor or file watcher adding a trailing space to one // of the block lines. Exact-byte strip would silently leave the block // in place. Sentinel-line strip must recover regardless. raw, err := os.ReadFile(path) require.NoError(t, err) mutated := bytes.Replace( raw, []byte("# [context] note\n"), []byte("# [context] note \n"), 1, ) require.NoError(t, os.WriteFile(path, mutated, 0o600)) stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped, "strip must succeed even after external mutation of block lines") got, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, original, string(got)) } func TestStripContextBlockTop_SecondCallIsNoop(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.go") original := []byte("package main\n") require.NoError(t, os.WriteFile(path, original, 0o600)) block := sentinelBlock("// [context] foo") require.NoError(t, diff.PrependContextBlock(path, block)) // First strip succeeds. stripped, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.True(t, stripped) // Second strip on the already-cleaned file must be a safe no-op. stripped2, err := diff.StripContextBlockTop(path, block) require.NoError(t, err) assert.False(t, stripped2) got, err := os.ReadFile(path) require.NoError(t, err) assert.True(t, bytes.Equal(original, got), "body must be unchanged after two strips") } func TestContextLineCount_ReturnsLinesPrependAdds(t *testing.T) { t.Parallel() block := sentinelBlock("// [context] one\n// two") // The block contains 3 internal newlines (between its 4 lines). Prepend // writes block + "\n", which adds 4 lines to the file. assert.Equal(t, 4, diff.ContextLineCount(block)) } func TestRestoreOriginal_NewFile(t *testing.T) { t.Parallel() dir := t.TempDir() filePath := filepath.Join(dir, "newfile.go") // Simulate the hook creating the file require.NoError(t, os.WriteFile(filePath, []byte("new content"), 0o600)) require.NoError(t, diff.RestoreOriginal(filePath, "", true)) _, err := os.Stat(filePath) assert.True(t, os.IsNotExist(err), "new file should be removed on restore") } func TestAppendContextBlock_OneBlankLineSeparator(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "file.rb") body := "end\n" require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) block := sentinelBlock("# [context] foo") require.NoError(t, diff.AppendContextBlock(path, block)) got, err := os.ReadFile(path) require.NoError(t, err) want := body + "\n" + block + "\n" assert.Equal(t, want, string(got)) }