| Josh Bleecher Snyder | 833a0f8 | 2025-04-24 18:39:36 +0000 | [diff] [blame] | 1 | package claudetool |
| 2 | |
| 3 | import ( |
| 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. |
| 21 | var 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. |
| 25 | func 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. |
| 44 | func 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 | |
| 80 | func 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. |
| 92 | func 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. |
| 117 | func 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 | |
| Josh Bleecher Snyder | 2fde465 | 2025-05-01 17:50:34 -0700 | [diff] [blame] | 143 | commitCleaner := strings.NewReplacer(initialCommit, "INITIAL_COMMIT_HASH") |
| 144 | got = commitCleaner.Replace(got) |
| 145 | want = commitCleaner.Replace(want) |
| 146 | |
| Josh Bleecher Snyder | 833a0f8 | 2025-04-24 18:39:36 +0000 | [diff] [blame] | 147 | if update { |
| 148 | archive.Files[i].Data = []byte(got) |
| 149 | break |
| 150 | } |
| 151 | if strings.TrimSpace(want) != strings.TrimSpace(got) { |
| 152 | t.Errorf("Results don't match.\nExpected:\n%s\n\nActual:\n%s", want, got) |
| 153 | } |
| 154 | |
| 155 | case ".run_autoformat": |
| 156 | if initialCommit == "" { |
| 157 | return fmt.Errorf("initial commit not set, cannot run autoformat") |
| 158 | } |
| 159 | |
| 160 | got, err := runAutoformat(dir, initialCommit) |
| 161 | if err != nil { |
| 162 | return fmt.Errorf("error running autoformat: %w", err) |
| 163 | } |
| 164 | slices.Sort(got) |
| 165 | |
| 166 | if update { |
| 167 | correct := strings.Join(got, "\n") + "\n" |
| 168 | archive.Files[i].Data = []byte(correct) |
| 169 | break |
| 170 | } |
| 171 | |
| 172 | want := strings.Split(strings.TrimSpace(string(file.Data)), "\n") |
| 173 | if !slices.Equal(want, got) { |
| 174 | t.Errorf("Formatted files don't match.\nExpected:\n%s\n\nActual:\n%s", want, got) |
| 175 | } |
| 176 | |
| 177 | default: |
| 178 | filePath := filepath.Join(dir, file.Name) |
| 179 | if err := os.MkdirAll(filepath.Dir(filePath), 0o700); err != nil { |
| 180 | return fmt.Errorf("error creating directory for %s: %w", file.Name, err) |
| 181 | } |
| 182 | data := file.Data |
| 183 | // Remove second trailing newline if present. |
| 184 | // An annoyance of the txtar format, messes with gofmt. |
| 185 | if bytes.HasSuffix(data, []byte("\n\n")) { |
| 186 | data = bytes.TrimSuffix(data, []byte("\n")) |
| 187 | } |
| 188 | if err := os.WriteFile(filePath, file.Data, 0o600); err != nil { |
| 189 | return fmt.Errorf("error writing file %s: %w", file.Name, err) |
| 190 | } |
| 191 | filesForNextCommit[file.Name] = true |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | return nil |
| 196 | } |
| 197 | |
| 198 | // makeGitCommit commits the specified files with the given message. |
| 199 | // Returns the commit hash. |
| 200 | func makeGitCommit(dir, message string, files map[string]bool) (string, error) { |
| 201 | for file := range files { |
| 202 | cmd := exec.Command("git", "add", file) |
| 203 | cmd.Dir = dir |
| 204 | if err := cmd.Run(); err != nil { |
| 205 | return "", fmt.Errorf("error staging file %s: %w", file, err) |
| 206 | } |
| 207 | } |
| 208 | message = cmp.Or(message, "Test commit") |
| 209 | |
| 210 | // Make the commit with fixed author, committer, and date for stable hashes |
| 211 | cmd := exec.Command("git", "commit", "--allow-empty", "-m", message) |
| 212 | cmd.Dir = dir |
| 213 | cmd.Env = gitCommitEnv() |
| 214 | if err := cmd.Run(); err != nil { |
| 215 | return "", fmt.Errorf("error making commit: %w", err) |
| 216 | } |
| 217 | |
| 218 | // Get the commit hash |
| 219 | cmd = exec.Command("git", "rev-parse", "HEAD") |
| 220 | cmd.Dir = dir |
| 221 | out, err := cmd.Output() |
| 222 | if err != nil { |
| 223 | return "", fmt.Errorf("error getting commit hash: %w", err) |
| 224 | } |
| 225 | |
| 226 | return strings.TrimSpace(string(out)), nil |
| 227 | } |
| 228 | |
| 229 | // runDifferentialTest runs the code review tool on the repository and returns the result. |
| 230 | func runDifferentialTest(dir, initialCommit string) (string, error) { |
| 231 | if initialCommit == "" { |
| 232 | return "", fmt.Errorf("initial commit not set, cannot run differential test") |
| 233 | } |
| 234 | |
| 235 | // Create a code reviewer for the repository |
| 236 | ctx := context.Background() |
| 237 | reviewer, err := NewCodeReviewer(ctx, dir, initialCommit) |
| 238 | if err != nil { |
| 239 | return "", fmt.Errorf("error creating code reviewer: %w", err) |
| 240 | } |
| 241 | |
| 242 | // Run the code review |
| 243 | result, err := reviewer.Run(ctx, nil) |
| 244 | if err != nil { |
| 245 | return "", fmt.Errorf("error running code review: %w", err) |
| 246 | } |
| 247 | |
| 248 | // Normalize paths in the result |
| 249 | normalized := normalizePaths(result, dir) |
| 250 | return normalized, nil |
| 251 | } |
| 252 | |
| 253 | // normalizePaths replaces the temp directory paths with a standard placeholder |
| 254 | func normalizePaths(result string, tempDir string) string { |
| 255 | return strings.ReplaceAll(result, tempDir, "/PATH/TO/REPO") |
| 256 | } |
| 257 | |
| 258 | // initGoModule initializes a Go module in the specified directory. |
| 259 | func initGoModule(dir string) error { |
| 260 | cmd := exec.Command("go", "mod", "init", "sketch.dev") |
| 261 | cmd.Dir = dir |
| 262 | return cmd.Run() |
| 263 | } |
| 264 | |
| 265 | // runAutoformat runs the autoformat function on the repository and returns the list of formatted files. |
| 266 | func runAutoformat(dir, initialCommit string) ([]string, error) { |
| 267 | if initialCommit == "" { |
| 268 | return nil, fmt.Errorf("initial commit not set, cannot run autoformat") |
| 269 | } |
| 270 | ctx := context.Background() |
| 271 | reviewer, err := NewCodeReviewer(ctx, dir, initialCommit) |
| 272 | if err != nil { |
| 273 | return nil, fmt.Errorf("error creating code reviewer: %w", err) |
| 274 | } |
| 275 | formattedFiles := reviewer.Autoformat(ctx) |
| 276 | normalizedFiles := make([]string, len(formattedFiles)) |
| 277 | for i, file := range formattedFiles { |
| 278 | normalizedFiles[i] = normalizePaths(file, dir) |
| 279 | } |
| 280 | slices.Sort(normalizedFiles) |
| 281 | return normalizedFiles, nil |
| 282 | } |
| 283 | |
| 284 | // resolveRealPath follows symlinks and returns the real path |
| 285 | // This handles platform-specific behaviors like macOS's /private prefix |
| 286 | func resolveRealPath(path string) string { |
| 287 | // Follow symlinks to get the real path |
| 288 | realPath, err := filepath.EvalSymlinks(path) |
| 289 | if err != nil { |
| 290 | // If we can't resolve symlinks, just return the original path |
| 291 | return path |
| 292 | } |
| 293 | return realPath |
| 294 | } |