builtin file operations
This commit is contained in:
26
object/builtin_read.go
Normal file
26
object/builtin_read.go
Normal 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
32
object/builtin_write.go
Normal 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{}
|
||||
}
|
||||
@@ -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 ...
|
||||
|
||||
Reference in New Issue
Block a user