blob: 405d046599190b9f4307ee98874ed85b6dae2fc6 [file] [log] [blame]
Sketch🕴️305f8172026-02-27 13:58:43 +04001package tools
2
3import (
4 "os"
Sketch🕴️00202652026-02-28 21:10:00 +04005 "path/filepath"
Sketch🕴️305f8172026-02-27 13:58:43 +04006)
7
8type FileReadArgs struct {
9 Path string `json:"path"`
10}
11
12func FileRead(args FileReadArgs) (string, error) {
13 if b, err := os.ReadFile(args.Path); err != nil {
14 return "", err
15 } else {
16 return string(b), nil
17 }
18}
19
20type FileWriteArgs struct {
21 Path string `json:"path"`
22 Contents string `json:"contents"`
23}
24
25type FileWriteResult struct {
26}
27
Sketch🕴️00202652026-02-28 21:10:00 +040028func sanitizePath(p string) (string, error) {
29 cwd, err := os.Getwd()
30 if err != nil {
31 return "", err
32 }
33 p = filepath.Join(cwd, p)
34 p, err = filepath.Rel(p, cwd)
35 if err != nil {
36 return "", err
37 }
38 return p, nil
39}
40
Sketch🕴️305f8172026-02-27 13:58:43 +040041func FileWrite(args FileWriteArgs) (string, error) {
Sketch🕴️00202652026-02-28 21:10:00 +040042 p, err := sanitizePath(args.Path)
43 if err != nil {
44 return "", err
45 }
46 if os.MkdirAll(filepath.Dir(p), 0666) != nil {
47 return "", nil
48 }
Sketch🕴️305f8172026-02-27 13:58:43 +040049 if err := os.WriteFile(args.Path, []byte(args.Contents), 0666); err != nil {
50 return "error", err
51 } else {
52 return "done", nil
53 }
54}
55
56type DirListArgs struct {
57 Name string `json:"name"`
58}
59
60type DirEntry struct {
61 Name string `json:"name"`
62 IsDir bool `json:"is_dir"`
63}
64
65type DirListResult struct {
66 Entries []DirEntry `json:"entries"`
67}
68
69func DirList(args DirListArgs) (DirListResult, error) {
70 dir := "."
71 if args.Name != "" {
72 dir = args.Name
73 }
74 entries, err := os.ReadDir(dir)
75 if err != nil {
76 return DirListResult{}, err
77 }
78 var ret DirListResult
79 for _, e := range entries {
80 ret.Entries = append(ret.Entries, DirEntry{
81 Name: e.Name(),
82 IsDir: e.IsDir(),
83 })
84 }
85 return ret, nil
86}