Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650package 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))}