builtin file operations
Some checks failed
Test / build (push) Waiting to run
Build / build (push) Has been cancelled

This commit is contained in:
Chuck Smith
2024-03-24 12:15:25 -04:00
parent b2d5badb5a
commit 5574c23597
3 changed files with 60 additions and 0 deletions

26
object/builtin_read.go Normal file
View File

@@ -0,0 +1,26 @@
package object
import (
"os"
)
// Read ...
func Read(args ...Object) Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
}
arg, ok := args[0].(*String)
if !ok {
return newError("argument to `read` expected to be `str` got=%T", args[0].Type())
}
filename := arg.Value
data, err := os.ReadFile(filename)
if err != nil {
return newError("error reading file: %s", err)
}
return &String{Value: string(data)}
}

32
object/builtin_write.go Normal file
View File

@@ -0,0 +1,32 @@
package object
import (
"os"
)
// Write ...
func Write(args ...Object) Object {
if len(args) != 2 {
return newError("wrong number of arguments. got=%d, want=2",
len(args))
}
arg, ok := args[0].(*String)
if !ok {
return newError("argument #1 to `write` expected to be `str` got=%T", args[0].Type())
}
filename := arg.Value
arg, ok = args[1].(*String)
if !ok {
return newError("argument #2 to `write` expected to be `str` got=%T", args[1].Type())
}
data := []byte(arg.Value)
err := os.WriteFile(filename, data, 0755)
if err != nil {
return newError("error writing file: %s", err)
}
return &Null{}
}

View File

@@ -27,6 +27,8 @@ var Builtins = map[string]*Builtin{
"join": {Name: "join", Fn: Join},
"split": {Name: "split", Fn: Split},
"find": {Name: "find", Fn: Find},
"read": {Name: "read", Fn: Read},
"write": {Name: "write", Fn: Write},
}
// BuiltinsIndex ...