diff --git a/compiler/stdlib/os.go b/compiler/stdlib/os.go index 4157ac6..d2c44b7 100644 --- a/compiler/stdlib/os.go +++ b/compiler/stdlib/os.go @@ -2,6 +2,7 @@ package stdlib import ( "io" + "io/ioutil" "os" "os/exec" @@ -78,6 +79,25 @@ var osModule = map[string]objects.Object{ "exec_look_path": FuncASRSE(exec.LookPath), // exec_look_path(file) => string/error "exec": &objects.UserFunction{Value: osExec}, // exec(name, args...) => command "stat": &objects.UserFunction{Value: osStat}, // stat(name) => imap(fileinfo)/error + "read_file": &objects.UserFunction{Value: osReadFile}, // readfile(name) => array(byte)/error +} + +func osReadFile(args ...objects.Object) (ret objects.Object, err error) { + if len(args) != 1 { + return nil, objects.ErrWrongNumArguments + } + + fname, ok := objects.ToString(args[0]) + if !ok { + return nil, objects.ErrInvalidTypeConversion + } + + bytes, err := ioutil.ReadFile(fname) + if err != nil { + return wrapError(err), nil + } + + return &objects.Bytes{Value: bytes}, nil } func osStat(args ...objects.Object) (ret objects.Object, err error) { diff --git a/compiler/stdlib/os_test.go b/compiler/stdlib/os_test.go index 9d7c73e..ea0b5b3 100644 --- a/compiler/stdlib/os_test.go +++ b/compiler/stdlib/os_test.go @@ -8,6 +8,29 @@ import ( "github.com/d5/tengo/objects" ) +func TestReadFile(t *testing.T) { + content := []byte("the quick brown fox jumps over the lazy dog") + tf, err := ioutil.TempFile("", "test") + if err != nil { + t.Logf("could not open tempfile: %s", err) + return + } + defer os.Remove(tf.Name()) + + _, err = tf.Write(content) + if err != nil { + t.Logf("could not write temp content: %s", err) + return + } + + tf.Close() + + module(t, "os").call("read_file", tf.Name()).expect(&objects.Bytes{Value: content}) +} + +func TestReadFileArgs(t *testing.T) { + module(t, "os").call("read_file").expectError() +} func TestFileStatArgs(t *testing.T) { module(t, "os").call("stat").expectError() } diff --git a/docs/stdlib-os.md b/docs/stdlib-os.md index d4751c1..934a006 100644 --- a/docs/stdlib-os.md +++ b/docs/stdlib-os.md @@ -63,6 +63,7 @@ os := import("os") - `lookup_env(key string) => string/false`: retrieves the value of the environment variable named by the key. - `mkdir(name string, perm int) => error `: creates a new directory with the specified name and permission bits (before umask). - `mkdir_all(name string, perm int) => error `: creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. +- `read_file(name string) => bytes/error `: reads the contents of a file into a byte array - `readlink(name string) => string/error `: returns the destination of the named symbolic link. - `remove(name string) => error `: removes the named file or (empty) directory. - `remove_all(name string) => error `: removes path and any children it contains.