-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrender.go
More file actions
75 lines (67 loc) · 1.78 KB
/
Copy pathrender.go
File metadata and controls
75 lines (67 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"os"
"strings"
"text/template"
)
func (ctx TemplateContext) render(tmpl string, output io.Writer) error {
t, err := template.New("template").Funcs(ctx.funcMap()).Parse(tmpl)
if err != nil {
return err
}
err = t.Execute(output, ctx)
if err != nil {
return err
}
return nil
}
func (ctx TemplateContext) funcMap() template.FuncMap {
return template.FuncMap{
"sh": ctx.inline,
"shell": ctx.codeBlock,
"raw": ctx.raw,
"csvToTable": csvToTable,
}
}
func csvToTable(input string) (string, error) {
r := csv.NewReader(strings.NewReader(input))
records, err := r.ReadAll()
if err != nil {
return "", fmt.Errorf("Failed to parse CSV: %s\n> Input: %s\n", err.Error(), input)
}
result := ""
if len(records) == 0 {
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, nil
}
func (ctx TemplateContext) OutputFile(meta TemplateMeta) (output io.WriteCloser, err error) {
if meta.Output == "" {
return os.Stdout, nil
}
tmpl, err := template.New("output").Funcs(ctx.funcMap()).Parse(meta.Output)
if err != nil {
return nil, fmt.Errorf("Failed to parse output name: %w", err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, ctx)
if err != nil {
return nil, fmt.Errorf("Failed to execute output name: %w", err)
}
filename := buf.String()
fmt.Printf("Saving result to %s\n", filename)
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return nil, fmt.Errorf("Failed to open the file: %w", err)
}
return file, nil
}