commit
e81380bb38
3 changed files with 44 additions and 0 deletions
|
@ -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) {
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
|
|
|
@ -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.
|
||||
|
|
Loading…
Reference in a new issue