a73x

internal/rewriter/rewriter_test.go

Ref:   Size: 2.2 KiB

package rewriter

import (
	"errors"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestStampUUIDsInsertsTagAfterClaude(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "foo.go")
	original := "package foo\n\n// @claude write a test\nfunc Foo() {}\n"
	if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
		t.Fatal(err)
	}

	err := StampUUIDs(path, map[int]string{3: "fw-a1b2c3d4"})
	if err != nil {
		t.Fatalf("StampUUIDs: %v", err)
	}

	got, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	want := "package foo\n\n// @claude[fw-a1b2c3d4] write a test\nfunc Foo() {}\n"
	if string(got) != want {
		t.Errorf("got:\n%s\nwant:\n%s", got, want)
	}
}

func TestStampUUIDsPreservesIndentation(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "foo.go")
	original := "func F() {\n    // @claude refactor\n}\n"
	if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
		t.Fatal(err)
	}

	if err := StampUUIDs(path, map[int]string{2: "fw-deadbeef"}); err != nil {
		t.Fatal(err)
	}
	got, _ := os.ReadFile(path)
	if !strings.Contains(string(got), "    // @claude[fw-deadbeef] refactor") {
		t.Errorf("indentation not preserved:\n%s", got)
	}
}

func TestStampUUIDsBlockComment(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "x.html")
	original := "<!-- @claude add aria -->\n<div></div>\n"
	if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := StampUUIDs(path, map[int]string{1: "fw-12345678"}); err != nil {
		t.Fatal(err)
	}
	got, _ := os.ReadFile(path)
	want := "<!-- @claude[fw-12345678] add aria -->\n<div></div>\n"
	if string(got) != want {
		t.Errorf("got:\n%s\nwant:\n%s", got, want)
	}
}

func TestAtomicReplaceAbortsOnStaleMtime(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "foo.go")
	if err := os.WriteFile(path, []byte("hi\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	tmpPath := filepath.Join(dir, "tmp")
	if err := os.WriteFile(tmpPath, []byte("bye\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	stale := time.Now().Add(-time.Hour)
	err := atomicReplace(path, tmpPath, 0o644, stale)
	if !errors.Is(err, ErrConcurrentModification) {
		t.Fatalf("got %v, want ErrConcurrentModification", err)
	}
}