mirror of
https://github.com/lancatlin/mdsh.git
synced 2026-11-05 19:30:12 +08:00
feat: add csvToTable function
This commit is contained in:
1 parent
534c27b6ca
commit
6fa452b123
2 files changed
+27
-6
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user