feat: add inline and block runner. Improve execution error handling

This commit is contained in:
Justin Lin committed 2025-07-25 12:23:47 +10:00
1 parent 8f764548b9
commit a2c99c710e
6 files changed
+218 -63

No files matched your search

+34
View File
@@ -3,7 +3,10 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os/exec"
"strings"
"text/template"
)
@@ -40,3 +43,34 @@ type ParamSpec struct {
}
type TemplateContext map[string]string
func (ctx TemplateContext) run(command string) (string, error) {
cmd := exec.Command("sh", "-c", command)
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stdout
for k, v := range ctx {
cmd.Env = append(cmd.Env, k+"="+v)
}
err := cmd.Run()
if err != nil {
return "", errors.New(stdout.String())
}
return stdout.String(), nil
}
func (ctx TemplateContext) codeBlock(command string) string {
out, err := ctx.run(command)
if err != nil {
return fmt.Sprintf("> Failed to execute the command:\n> `%s`\n> %s\n", command, err.Error())
}
return fmt.Sprintf("\n```\n%s\n```\n", out)
}
func (ctx TemplateContext) inline(command string) string {
out, err := ctx.run(command)
if err != nil {
return fmt.Sprintf("`Failed to execute the command: '%s'. %s`", command, err.Error())
}
return fmt.Sprintf("`%s`", strings.Trim(out, "\n "))
}