zk/adapter/handlebars/helpers/shell.go

31 lines
768 B
Go
Raw Normal View History

2020-12-27 17:58:22 +00:00
package helpers
import (
"strings"
"github.com/aymerick/raymond"
"github.com/mickael-menu/zk/util"
"github.com/mickael-menu/zk/util/exec"
2020-12-27 17:58:22 +00:00
)
// RegisterShell registers the {{sh}} template helper, which runs shell commands.
//
// {{#sh "tr '[a-z]' '[A-Z]'"}}Hello, world!{{/sh}} -> HELLO, WORLD!
// {{sh "echo 'Hello, world!'"}} -> Hello, world!
func RegisterShell(logger util.Logger) {
raymond.RegisterHelper("sh", func(arg string, options *raymond.Options) string {
cmd := exec.CommandFromString(arg)
2020-12-27 17:58:22 +00:00
// Feed any block content as piped input
cmd.Stdin = strings.NewReader(options.Fn())
output, err := cmd.Output()
if err != nil {
logger.Printf("{{sh}} command failed: %v", err)
return ""
}
2021-01-30 14:24:08 +00:00
return strings.TrimSpace(string(output))
2020-12-27 17:58:22 +00:00
})
}