Skip to content

Commit

Permalink
write file
Browse files Browse the repository at this point in the history
  • Loading branch information
mandelsoft committed Jan 31, 2019
1 parent df5de11 commit 855523c
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ Contents:
- [(( read("file.yml") ))](#-readfileyml-)
- [(( exec("command", arg1, arg2) ))](#-execcommand-arg1-arg2-)
- [(( pipe(data, "command", arg1, arg2) ))](#-pipedata-command-arg1-arg2-)
- [(( write("file.yml", data) ))](#-writefileyml-data-)
- [X509 Functions](#x509-functions)
- [(( x509genkey(spec) ))](#-x509genkeyspec-)
- [(( x509publickey(key) ))](#-x509publickeykey-)
Expand Down Expand Up @@ -2146,6 +2147,12 @@ Alternatively `pipe` can be called with data and a list argument completely desc

The same command will be executed once, only, even if it is used in multiple expressions.

#### `(( write("file.yml", data) ))`

Write a file and return its content. If the result can be parsed as yaml document,
the document is returned. An optional 3rd argument can be used to pass the
file permissions (default is `0644`).


### X509 Functions

Expand Down
2 changes: 2 additions & 0 deletions dynaml/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ func (e CallExpr) Evaluate(binding Binding, locally bool) (interface{}, Evaluati
result, sub, ok = func_read(true, values, binding)
case "read_uncached":
result, sub, ok = func_read(false, values, binding)
case "write":
result, sub, ok = func_write(values, binding)

case "format":
result, sub, ok = func_format(values, binding)
Expand Down
42 changes: 42 additions & 0 deletions dynaml/write.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package dynaml

import (
"io/ioutil"
"os"
"strconv"
)

func func_write(arguments []interface{}, binding Binding) (interface{}, EvaluationInfo, bool) {
var err error
info := DefaultInfo()

if len(arguments) < 2 || len(arguments) > 3 {
return info.Error("write requires two arguments")
}
file, ok := getArg(0, arguments[0])
if !ok || file == "" {
return info.Error("file argument must be a non-empty string")
}
data, _ := getArg(1, arguments[1])
permissions := int64(0644)
if len(arguments) == 3 {
switch v := arguments[2].(type) {
case string:
permissions, err = strconv.ParseInt(v, 10, 64)
if err != nil {
return info.Error("permissions must be given as int or int string: %s", err)
}
case int64:
permissions = v
default:
return info.Error("permissions must be given as int or int string")
}
}

err = ioutil.WriteFile(file, []byte(data), os.FileMode(permissions))
if err != nil {
return info.Error("cannot write file: %s", err)
}

return convertOutput([]byte(data))
}

0 comments on commit 855523c

Please sign in to comment.