blob: 405d046599190b9f4307ee98874ed85b6dae2fc6 [file] [log] [blame]
package tools
import (
"os"
"path/filepath"
)
type FileReadArgs struct {
Path string `json:"path"`
}
func FileRead(args FileReadArgs) (string, error) {
if b, err := os.ReadFile(args.Path); err != nil {
return "", err
} else {
return string(b), nil
}
}
type FileWriteArgs struct {
Path string `json:"path"`
Contents string `json:"contents"`
}
type FileWriteResult struct {
}
func sanitizePath(p string) (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
p = filepath.Join(cwd, p)
p, err = filepath.Rel(p, cwd)
if err != nil {
return "", err
}
return p, nil
}
func FileWrite(args FileWriteArgs) (string, error) {
p, err := sanitizePath(args.Path)
if err != nil {
return "", err
}
if os.MkdirAll(filepath.Dir(p), 0666) != nil {
return "", nil
}
if err := os.WriteFile(args.Path, []byte(args.Contents), 0666); err != nil {
return "error", err
} else {
return "done", nil
}
}
type DirListArgs struct {
Name string `json:"name"`
}
type DirEntry struct {
Name string `json:"name"`
IsDir bool `json:"is_dir"`
}
type DirListResult struct {
Entries []DirEntry `json:"entries"`
}
func DirList(args DirListArgs) (DirListResult, error) {
dir := "."
if args.Name != "" {
dir = args.Name
}
entries, err := os.ReadDir(dir)
if err != nil {
return DirListResult{}, err
}
var ret DirListResult
for _, e := range entries {
ret.Entries = append(ret.Entries, DirEntry{
Name: e.Name(),
IsDir: e.IsDir(),
})
}
return ret, nil
}