1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "testing"
12 "unicode/utf8"
13
14 "github.com/bnema/zut/packages/provider"
15)
16
17func TestASTToolReportsMissingBackend(t *testing.T) {
18 tool := &ASTTool{CWD: t.TempDir(), LookPath: func(string) (string, error) { return "", os.ErrNotExist }}
19 _, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"$A","language":"go","path":"."}`), nil)
20 if err == nil || !strings.Contains(err.Error(), "ast-grep executable ('ast-grep' or 'sg') not found") {
21 t.Fatalf("Execute error = %v", err)
22 }
23}
24
25func TestASTToolReportsCaptureLimitWithoutBrokenPipe(t *testing.T) {
26 if runtime.GOOS == "windows" {
27 t.Skip("test fixture uses a POSIX script")
28 }
29 root := t.TempDir()
30 script := filepath.Join(root, "sg")
31 body := "#!/bin/sh\nhead -c 4194305 /dev/zero | tr '\\0' x\n"
32 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
33 t.Fatal(err)
34 }
35 tool := &ASTTool{CWD: root, LookPath: func(string) (string, error) { return script, nil }}
36 _, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"$A","language":"go","path":"."}`), nil)
37 if err == nil || !strings.Contains(err.Error(), "output exceeds") || strings.Contains(strings.ToLower(err.Error()), "broken pipe") {
38 t.Fatalf("Execute error = %v", err)
39 }
40}
41
42func TestASTToolExecutesWithoutShellAndTracksDiscoveredFiles(t *testing.T) {
43 if runtime.GOOS == "windows" {
44 t.Skip("test fixture uses a POSIX script")
45 }
46 root := t.TempDir()
47 script := filepath.Join(root, "sg")
48 body := "#!/bin/sh\nprintf '%s\\n' '{\"file\":\"main.go\",\"range\":{}}'\n"
49 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
50 t.Fatal(err)
51 }
52 tool := &ASTTool{CWD: root, LookPath: func(string) (string, error) { return script, nil }}
53 result, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"fmt.Errorf($MSG)","language":"go","path":"."}`), nil)
54 if err != nil {
55 t.Fatalf("Execute: %v", err)
56 }
57 want := filepath.Join(root, "main.go")
58 if len(result.Context.Discovers) != 1 || result.Context.Discovers[0] != want {
59 t.Fatalf("discoveries = %v, want %s", result.Context.Discovers, want)
60 }
61}
62
63func TestASTToolPrefersArchExecutableName(t *testing.T) {
64 root := t.TempDir()
65 var lookedUp []string
66 tool := &ASTTool{CWD: root, LookPath: func(name string) (string, error) {
67 lookedUp = append(lookedUp, name)
68 if name == "ast-grep" {
69 return "/usr/bin/ast-grep", nil
70 }
71 return "", os.ErrNotExist
72 }}
73 got, err := tool.executable()
74 if err != nil || got != "/usr/bin/ast-grep" || len(lookedUp) != 1 {
75 t.Fatalf("executable = %q, %v; lookups = %v", got, err, lookedUp)
76 }
77}
78
79func TestASTToolRewritePreviewAndExecute(t *testing.T) {
80 binary, err := exec.LookPath("ast-grep")
81 if err != nil {
82 t.Skip("ast-grep not installed")
83 }
84 root := t.TempDir()
85 path := filepath.Join(root, "main.go")
86 original := "package main\nfunc main() { println(\"x\") }\n"
87 if err := os.WriteFile(path, []byte(original), 0o640); err != nil {
88 t.Fatal(err)
89 }
90 tool := &ASTTool{CWD: root, LookPath: func(string) (string, error) { return binary, nil }}
91 args := json.RawMessage(`{"pattern":"println($A)","language":"go","path":".","rewrite":"fmt.Println($A)"}`)
92 preview, err := tool.Preview(context.Background(), args)
93 if err != nil {
94 t.Fatalf("Preview: %v", err)
95 }
96 if !strings.Contains(preview.Content[0].(provider.TextBlock).Text, "+func main() { fmt.Println") {
97 t.Fatalf("preview = %q", preview.Content[0].(provider.TextBlock).Text)
98 }
99 if got, _ := os.ReadFile(path); string(got) != original {
100 t.Fatal("preview modified the file")
101 }
102 result, err := tool.Execute(context.Background(), args, nil)
103 if err != nil {
104 t.Fatalf("Execute: %v", err)
105 }
106 got, _ := os.ReadFile(path)
107 if !strings.Contains(string(got), "fmt.Println") || len(result.Context.Mutates) != 1 {
108 t.Fatalf("result = %q, context = %+v", got, result.Context)
109 }
110 if info, _ := os.Stat(path); info.Mode().Perm() != 0o640 {
111 t.Fatalf("mode = %v", info.Mode().Perm())
112 }
113}
114
115func TestASTRewriteFormatsGoSource(t *testing.T) {
116 root := t.TempDir()
117 path := filepath.Join(root, "main.go")
118 original := []byte("package main\nfunc add(left, right int) int { return left + right\n }\n")
119 if err := os.WriteFile(path, original, 0o644); err != nil {
120 t.Fatal(err)
121 }
122 match := astTestMatch(path, "return left + right\n ", "\nreturn left + right\n\n", 45, 66)
123 plan, err := (&ASTTool{CWD: root}).planRewrite(root, astArgs{Language: "go", Rewrite: "{$$$BODY}"}, []astMatch{match})
124 if err != nil {
125 t.Fatalf("planRewrite: %v", err)
126 }
127 want := "package main\n\nfunc add(left, right int) int {\n\treturn left + right\n\n}\n"
128 if got := string(plan.changes[0].content); got != want {
129 t.Fatalf("rewrite = %q, want %q", got, want)
130 }
131}
132
133func TestASTRewriteUsesOutermostNestedMatch(t *testing.T) {
134 root := t.TempDir()
135 path := filepath.Join(root, "main.go")
136 original := []byte("package main\nfunc main() { f(g(x)) }\n")
137 if err := os.WriteFile(path, original, 0o644); err != nil {
138 t.Fatal(err)
139 }
140 matches := []astMatch{
141 astTestMatch(path, "f(g(x))", "WRAP(f)", 27, 34),
142 astTestMatch(path, "g(x)", "WRAP(g)", 29, 33),
143 }
144 plan, err := (&ASTTool{CWD: root}).planRewrite(root, astArgs{Rewrite: "WRAP($A)"}, matches)
145 if err != nil {
146 t.Fatalf("planRewrite: %v", err)
147 }
148 if got := string(plan.changes[0].content); !strings.Contains(got, "WRAP(f)") || strings.Contains(got, "WRAP(g)") {
149 t.Fatalf("rewrite = %q", got)
150 }
151}
152
153func astTestMatch(path, text, replacement string, start, end int) astMatch {
154 match := astMatch{File: path, Text: text, Replacement: replacement}
155 match.Range.ByteOffset.Start = start
156 match.Range.ByteOffset.End = end
157 return match
158}
159
160func TestBoundASTTextPreservesUTF8(t *testing.T) {
161 got := boundASTText(strings.Repeat("界", maxASTOutputBytes))
162 if !strings.Contains(got, "truncated") || !utf8.ValidString(got) {
163 t.Fatalf("invalid bounded output")
164 }
165}