funcs: Add exec

This commit is contained in:
adnano 2021-05-22 20:41:52 -04:00
parent bc7174e9e7
commit 40322facd2
2 changed files with 17 additions and 6 deletions

16
dir.go
View file

@ -114,7 +114,9 @@ func (d *Dir) _read(srcDir, path string, task *Task, cfg *Site) error {
} }
if cmd, ok := task.Preprocess[strings.TrimPrefix(ext, ".")]; ok { if cmd, ok := task.Preprocess[strings.TrimPrefix(ext, ".")]; ok {
content = process(cmd, bytes.NewReader(content)) var buf bytes.Buffer
execute(cmd, bytes.NewReader(content), &buf)
content = buf.Bytes()
} }
page.Content = string(content) page.Content = string(content)
@ -228,7 +230,9 @@ func (d *Dir) write(dstDir string, task *Task) error {
} }
var content []byte var content []byte
if cmd := task.Postprocess; cmd != "" { if cmd := task.Postprocess; cmd != "" {
content = process(cmd, strings.NewReader(page.Content)) var buf bytes.Buffer
execute(cmd, strings.NewReader(page.Content), &buf)
content = buf.Bytes()
} else { } else {
content = []byte(page.Content) content = []byte(page.Content)
} }
@ -290,17 +294,17 @@ func (d *Dir) sort() {
} }
} }
// process runs a process command. // execute runs a command.
func process(command string, input io.Reader) []byte { func execute(command string, input io.Reader, output io.Writer) {
split := strings.Split(command, " ") split := strings.Split(command, " ")
cmd := exec.Command(split[0], split[1:]...) cmd := exec.Command(split[0], split[1:]...)
cmd.Stdin = input cmd.Stdin = input
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
output, err := cmd.Output() cmd.Stdout = output
err := cmd.Run()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
return output
} }
func (d *Dir) Title() string { func (d *Dir) Title() string {

View file

@ -11,6 +11,7 @@ import (
func (s *Site) funcs() map[string]interface{} { func (s *Site) funcs() map[string]interface{} {
return map[string]interface{}{ return map[string]interface{}{
"dir": s.dir, "dir": s.dir,
"exec": executeString,
"page": s.page, "page": s.page,
"path": func() _path { return _path{} }, "path": func() _path { return _path{} },
"partial": s.templates.ExecutePartial, "partial": s.templates.ExecutePartial,
@ -54,6 +55,12 @@ func (_strings) TrimRight(a, b string) string { return strings.TrimRight
func (_strings) TrimSpace(s string) string { return strings.TrimSpace(s) } func (_strings) TrimSpace(s string) string { return strings.TrimSpace(s) }
func (_strings) TrimSuffix(a, b string) string { return strings.TrimSuffix(a, b) } func (_strings) TrimSuffix(a, b string) string { return strings.TrimSuffix(a, b) }
func executeString(command, input string) string {
var b strings.Builder
execute(command, strings.NewReader(input), &b)
return b.String()
}
func reverse(s interface{}) interface{} { func reverse(s interface{}) interface{} {
v := reflect.ValueOf(s) v := reflect.ValueOf(s)
n := v.Len() n := v.Len()