feat: throw error when shell execution failed

This commit is contained in:
Justin Lin committed 2025-07-31 12:27:38 +10:00
1 parent 6fa452b123
commit 5d58e581d0
2 files changed
+15 -17

No files matched your search

+10 -12
View File
@@ -2,7 +2,6 @@ package main
import (
"bytes"
"errors"
"fmt"
"os/exec"
"strings"
@@ -18,32 +17,31 @@ func (ctx TemplateContext) run(command string) (string, error) {
}
err := cmd.Run()
if err != nil {
return "", errors.New(stdout.String())
return "", fmt.Errorf("Failed to execute the command:\nCommand: `%s`\nError: %s\n", command, stdout.String())
}
return stdout.String(), nil
}
func (ctx TemplateContext) raw(command string) string {
func (ctx TemplateContext) raw(command string) (string, error) {
out, err := ctx.run(command)
if err != nil {
fmt.Println(err)
return "error"
return "", err
}
return strings.TrimSpace(out)
return strings.TrimSpace(out), nil
}
func (ctx TemplateContext) codeBlock(command string) string {
func (ctx TemplateContext) codeBlock(command string) (string, error) {
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 "", err
}
return fmt.Sprintf("\n```\n%s\n```\n", out)
return fmt.Sprintf("\n```\n%s\n```\n", out), nil
}
func (ctx TemplateContext) inline(command string) string {
func (ctx TemplateContext) inline(command string) (string, error) {
out, err := ctx.run(command)
if err != nil {
return fmt.Sprintf("`Failed to execute the command: '%s'. %s`", command, err.Error())
return "", err
}
return fmt.Sprintf("`%s`", strings.Trim(out, "\n "))
return fmt.Sprintf("`%s`", strings.Trim(out, "\n ")), nil
}
+5 -5
View File
@@ -11,7 +11,7 @@ import (
)
func (ctx TemplateContext) render(tmpl string, output io.Writer) error {
t, err := template.New("foo").Funcs(ctx.funcMap()).Parse(tmpl)
t, err := template.New("template").Funcs(ctx.funcMap()).Parse(tmpl)
if err != nil {
return err
}
@@ -31,22 +31,22 @@ func (ctx TemplateContext) funcMap() template.FuncMap {
}
}
func csvToTable(input string) string {
func csvToTable(input string) (string, error) {
r := csv.NewReader(strings.NewReader(input))
records, err := r.ReadAll()
if err != nil {
return fmt.Sprintf("> Failed to parse CSV: %s\n> Input: %s\n", err.Error(), input)
return "", fmt.Errorf("Failed to parse CSV: %s\n> Input: %s\n", err.Error(), input)
}
result := ""
if len(records) == 0 {
return fmt.Sprintf("Error: records is empty: %s\n", input)
return "", fmt.Errorf("Error: records is empty: %s\n", input)
}
result += "| " + strings.Join(records[0], " | ") + " |\n"
result += "|" + strings.Repeat(" --- |", len(records[0])) + "\n"
for _, row := range records[1:] {
result += "| " + strings.Join(row, " | ") + " |\n"
}
return result
return result, nil
}
func (ctx TemplateContext) OutputFile(meta TemplateMeta) (output io.WriteCloser, err error) {