feat: add csvToTable function

This commit is contained in:
Justin Lin committed 2025-07-31 10:43:50 +10:00
1 parent 534c27b6ca
commit 6fa452b123
2 files changed
+27 -6

No files matched your search

+24 -3
View File
@@ -2,9 +2,11 @@ package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"os"
"strings"
"text/template"
)
@@ -22,12 +24,31 @@ func (ctx TemplateContext) render(tmpl string, output io.Writer) error {
func (ctx TemplateContext) funcMap() template.FuncMap {
return template.FuncMap{
"sh": ctx.inline,
"shell": ctx.codeBlock,
"raw": ctx.raw,
"sh": ctx.inline,
"shell": ctx.codeBlock,
"raw": ctx.raw,
"csvToTable": csvToTable,
}
}
func csvToTable(input string) string {
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)
}
result := ""
if len(records) == 0 {
return fmt.Sprintf("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
}
func (ctx TemplateContext) OutputFile(meta TemplateMeta) (output io.WriteCloser, err error) {
if meta.Output == "" {
return os.Stdout, nil