blob: 71934a20a76aac625b67af989113755d65f34465 [file] [log] [blame]
Josh Bleecher Snyder833a0f82025-04-24 18:39:36 +00001package claudetool
2
3import (
4 "bytes"
5 "cmp"
6 "context"
7 "flag"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "slices"
13 "strings"
14 "testing"
15
16 "golang.org/x/tools/txtar"
17)
18
19// updateTests is set to true when the -update flag is used.
20// This will update the expected test results instead of failing tests.
21var updateTests = flag.Bool("update", false, "update expected test results instead of failing tests")
22
23// TestCodereviewDifferential runs all the end-to-end tests for the codereview and differential packages.
24// Each test is defined in a .txtar file in the testdata directory.
25func TestCodereviewDifferential(t *testing.T) {
26 entries, err := os.ReadDir("testdata")
27 if err != nil {
28 t.Fatalf("failed to read testdata directory: %v", err)
29 }
30 for _, entry := range entries {
31 if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".txtar") {
32 continue
33 }
34 testPath := filepath.Join("testdata", entry.Name())
35 testName := strings.TrimSuffix(entry.Name(), ".txtar")
36 t.Run(testName, func(t *testing.T) {
37 t.Parallel()
38 runE2ETest(t, testPath, *updateTests)
39 })
40 }
41}
42
43// runE2ETest executes a single end-to-end test from a .txtar file.
44func runE2ETest(t *testing.T, testPath string, update bool) {
45 orig, err := os.ReadFile(testPath)
46 if err != nil {
47 t.Fatalf("failed to read test file %s: %v", testPath, err)
48 }
49 archive, err := txtar.ParseFile(testPath)
50 if err != nil {
51 t.Fatalf("failed to parse txtar file %s: %v", testPath, err)
52 }
53
54 tmpDir := t.TempDir()
55 // resolve temp dir path so that we can canonicalize/normalize it later
56 tmpDir = resolveRealPath(tmpDir)
57
58 if err := initGoModule(tmpDir); err != nil {
59 t.Fatalf("failed to initialize Go module: %v", err)
60 }
61 if err := initGitRepo(tmpDir); err != nil {
62 t.Fatalf("failed to initialize git repository: %v", err)
63 }
64 if err := processTestFiles(t, archive, tmpDir, update); err != nil {
65 t.Fatalf("error processing test files: %v", err)
66 }
67
68 // If we're updating, write back the modified archive to the file
69 if update {
70 updatedContent := txtar.Format(archive)
71 // only write back changes, avoids git status churn
72 if !bytes.Equal(orig, updatedContent) {
73 if err := os.WriteFile(testPath, updatedContent, 0o644); err != nil {
74 t.Errorf("Failed to update test file %s: %v", testPath, err)
75 }
76 }
77 }
78}
79
80func gitCommitEnv() []string {
81 return append(os.Environ(),
82 "GIT_AUTHOR_NAME=Test Author",
83 "GIT_AUTHOR_EMAIL=test@example.com",
84 "GIT_COMMITTER_NAME=Test Committer",
85 "GIT_COMMITTER_EMAIL=test@example.com",
86 "GIT_AUTHOR_DATE=2025-01-01T00:00:00Z",
87 "GIT_COMMITTER_DATE=2025-01-01T00:00:00Z",
88 )
89}
90
91// initGitRepo initializes a new git repository in the specified directory.
92func initGitRepo(dir string) error {
93 cmd := exec.Command("git", "init")
94 cmd.Dir = dir
95 err := cmd.Run()
96 if err != nil {
97 return fmt.Errorf("error initializing git repository: %w", err)
98 }
99 // create a single commit out of everything there now
100 cmd = exec.Command("git", "add", ".")
101 cmd.Dir = dir
102 err = cmd.Run()
103 if err != nil {
104 return fmt.Errorf("error staging files: %w", err)
105 }
106 cmd = exec.Command("git", "commit", "-m", "create repo")
107 cmd.Dir = dir
108 cmd.Env = gitCommitEnv()
109 err = cmd.Run()
110 if err != nil {
111 return fmt.Errorf("error making initial commit: %w", err)
112 }
113 return nil
114}
115
116// processTestFiles processes the files in the txtar archive in sequence.
117func processTestFiles(t *testing.T, archive *txtar.Archive, dir string, update bool) error {
118 var initialCommit string
119 filesForNextCommit := make(map[string]bool)
120
121 for i, file := range archive.Files {
122 switch file.Name {
123 case ".commit":
124 commit, err := makeGitCommit(dir, string(file.Data), filesForNextCommit)
125 if err != nil {
126 return fmt.Errorf("error making git commit: %w", err)
127 }
128 clear(filesForNextCommit)
129 initialCommit = cmp.Or(initialCommit, commit)
130 // fmt.Println("initial commit:", initialCommit)
131 // cmd := exec.Command("git", "log")
132 // cmd.Dir = dir
133 // cmd.Stdout = os.Stdout
134 // cmd.Run()
135
136 case ".run_test":
137 got, err := runDifferentialTest(dir, initialCommit)
138 if err != nil {
139 return fmt.Errorf("error running differential test: %w", err)
140 }
141 want := string(file.Data)
142
143 if update {
144 archive.Files[i].Data = []byte(got)
145 break
146 }
147 if strings.TrimSpace(want) != strings.TrimSpace(got) {
148 t.Errorf("Results don't match.\nExpected:\n%s\n\nActual:\n%s", want, got)
149 }
150
151 case ".run_autoformat":
152 if initialCommit == "" {
153 return fmt.Errorf("initial commit not set, cannot run autoformat")
154 }
155
156 got, err := runAutoformat(dir, initialCommit)
157 if err != nil {
158 return fmt.Errorf("error running autoformat: %w", err)
159 }
160 slices.Sort(got)
161
162 if update {
163 correct := strings.Join(got, "\n") + "\n"
164 archive.Files[i].Data = []byte(correct)
165 break
166 }
167
168 want := strings.Split(strings.TrimSpace(string(file.Data)), "\n")
169 if !slices.Equal(want, got) {
170 t.Errorf("Formatted files don't match.\nExpected:\n%s\n\nActual:\n%s", want, got)
171 }
172
173 default:
174 filePath := filepath.Join(dir, file.Name)
175 if err := os.MkdirAll(filepath.Dir(filePath), 0o700); err != nil {
176 return fmt.Errorf("error creating directory for %s: %w", file.Name, err)
177 }
178 data := file.Data
179 // Remove second trailing newline if present.
180 // An annoyance of the txtar format, messes with gofmt.
181 if bytes.HasSuffix(data, []byte("\n\n")) {
182 data = bytes.TrimSuffix(data, []byte("\n"))
183 }
184 if err := os.WriteFile(filePath, file.Data, 0o600); err != nil {
185 return fmt.Errorf("error writing file %s: %w", file.Name, err)
186 }
187 filesForNextCommit[file.Name] = true
188 }
189 }
190
191 return nil
192}
193
194// makeGitCommit commits the specified files with the given message.
195// Returns the commit hash.
196func makeGitCommit(dir, message string, files map[string]bool) (string, error) {
197 for file := range files {
198 cmd := exec.Command("git", "add", file)
199 cmd.Dir = dir
200 if err := cmd.Run(); err != nil {
201 return "", fmt.Errorf("error staging file %s: %w", file, err)
202 }
203 }
204 message = cmp.Or(message, "Test commit")
205
206 // Make the commit with fixed author, committer, and date for stable hashes
207 cmd := exec.Command("git", "commit", "--allow-empty", "-m", message)
208 cmd.Dir = dir
209 cmd.Env = gitCommitEnv()
210 if err := cmd.Run(); err != nil {
211 return "", fmt.Errorf("error making commit: %w", err)
212 }
213
214 // Get the commit hash
215 cmd = exec.Command("git", "rev-parse", "HEAD")
216 cmd.Dir = dir
217 out, err := cmd.Output()
218 if err != nil {
219 return "", fmt.Errorf("error getting commit hash: %w", err)
220 }
221
222 return strings.TrimSpace(string(out)), nil
223}
224
225// runDifferentialTest runs the code review tool on the repository and returns the result.
226func runDifferentialTest(dir, initialCommit string) (string, error) {
227 if initialCommit == "" {
228 return "", fmt.Errorf("initial commit not set, cannot run differential test")
229 }
230
231 // Create a code reviewer for the repository
232 ctx := context.Background()
233 reviewer, err := NewCodeReviewer(ctx, dir, initialCommit)
234 if err != nil {
235 return "", fmt.Errorf("error creating code reviewer: %w", err)
236 }
237
238 // Run the code review
239 result, err := reviewer.Run(ctx, nil)
240 if err != nil {
241 return "", fmt.Errorf("error running code review: %w", err)
242 }
243
244 // Normalize paths in the result
245 normalized := normalizePaths(result, dir)
246 return normalized, nil
247}
248
249// normalizePaths replaces the temp directory paths with a standard placeholder
250func normalizePaths(result string, tempDir string) string {
251 return strings.ReplaceAll(result, tempDir, "/PATH/TO/REPO")
252}
253
254// initGoModule initializes a Go module in the specified directory.
255func initGoModule(dir string) error {
256 cmd := exec.Command("go", "mod", "init", "sketch.dev")
257 cmd.Dir = dir
258 return cmd.Run()
259}
260
261// runAutoformat runs the autoformat function on the repository and returns the list of formatted files.
262func runAutoformat(dir, initialCommit string) ([]string, error) {
263 if initialCommit == "" {
264 return nil, fmt.Errorf("initial commit not set, cannot run autoformat")
265 }
266 ctx := context.Background()
267 reviewer, err := NewCodeReviewer(ctx, dir, initialCommit)
268 if err != nil {
269 return nil, fmt.Errorf("error creating code reviewer: %w", err)
270 }
271 formattedFiles := reviewer.Autoformat(ctx)
272 normalizedFiles := make([]string, len(formattedFiles))
273 for i, file := range formattedFiles {
274 normalizedFiles[i] = normalizePaths(file, dir)
275 }
276 slices.Sort(normalizedFiles)
277 return normalizedFiles, nil
278}
279
280// resolveRealPath follows symlinks and returns the real path
281// This handles platform-specific behaviors like macOS's /private prefix
282func resolveRealPath(path string) string {
283 // Follow symlinks to get the real path
284 realPath, err := filepath.EvalSymlinks(path)
285 if err != nil {
286 // If we can't resolve symlinks, just return the original path
287 return path
288 }
289 return realPath
290}