| 1 | package builtin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/tool" |
| 11 | ) |
| 12 | |
| 13 | // The file tools are how a Windows session changes a file without PowerShell's |
| 14 | // ANSI/UTF-16 defaults, so each one must write back the charset and BOM it found. |
| 15 | func TestFileToolsKeepEncodingAndBOM(t *testing.T) { |
| 16 | const before, after = "标题:旧的说明\r\n第二行\r\n", "标题:新的说明\r\n第二行\r\n" |
| 17 | bom := []byte{0xEF, 0xBB, 0xBF} |
| 18 | encodings := []struct { |
| 19 | name string |
| 20 | encode func(string) []byte |
| 21 | }{ |
| 22 | {"gbk", func(s string) []byte { return gbkBytes(t, s) }}, |
| 23 | {"utf8", func(s string) []byte { return []byte(s) }}, |
| 24 | {"utf8-bom", func(s string) []byte { return append(append([]byte{}, bom...), s...) }}, |
| 25 | } |
| 26 | ops := []struct { |
| 27 | name string |
| 28 | args func(path string) map[string]any |
| 29 | }{ |
| 30 | {"edit_file", func(path string) map[string]any { |
| 31 | return map[string]any{"path": path, "old_string": "旧的", "new_string": "新的"} |
| 32 | }}, |
| 33 | {"multi_edit", func(path string) map[string]any { |
| 34 | return map[string]any{"path": path, "edits": []map[string]any{{"old_string": "旧的", "new_string": "新的"}}} |
| 35 | }}, |
| 36 | {"write_file", func(path string) map[string]any { |
| 37 | return map[string]any{"path": path, "content": after} |
| 38 | }}, |
| 39 | } |
| 40 | for _, enc := range encodings { |
| 41 | for _, op := range ops { |
| 42 | t.Run(enc.name+"/"+op.name, func(t *testing.T) { |
| 43 | path := filepath.Join(t.TempDir(), "f.txt") |
| 44 | if err := os.WriteFile(path, enc.encode(before), 0o644); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | tl, ok := tool.LookupBuiltin(op.name) |
| 48 | if !ok { |
| 49 | t.Fatalf("%s not registered", op.name) |
| 50 | } |
| 51 | if _, err := tl.Execute(context.Background(), e2eArgs(op.args(path))); err != nil { |
| 52 | t.Fatalf("%s: %v", op.name, err) |
| 53 | } |
| 54 | got, err := os.ReadFile(path) |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if want := enc.encode(after); !bytes.Equal(got, want) { |
| 59 | t.Fatalf("on disk % x\nwant % x", got, want) |
| 60 | } |
| 61 | }) |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 |