-
Notifications
You must be signed in to change notification settings - Fork 3
/
template.go
94 lines (84 loc) · 1.72 KB
/
template.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package help
import (
"bytes"
"encoding/json"
"fmt"
"go/build"
"log"
"os"
"path"
"text/template"
"github.com/jackdoe/baxx/common"
)
type HelpObject struct {
Template TextTemplate
Err error
Status *common.UserStatusOutput
Notifications []common.FileNotification
FilePath string
Protected bool
Method string
SeeAlso []HelpSeeAlso
Token string
Email string
}
type HelpSeeAlso struct {
Method string
Path string
}
const (
empty = ""
tab = "\t"
)
func PrettyJson(data interface{}) (string, error) {
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent(empty, tab)
err := encoder.Encode(data)
if err != nil {
return empty, err
}
return buffer.String(), nil
}
func Load() *template.Template {
fm := template.FuncMap{
"add": func(a, b uint64) uint64 {
return a + b
},
"prettySize": func(size uint64) string {
return common.PrettySize(size)
},
"prettyFloat": func(p float64) string {
return fmt.Sprintf("%.2f", p)
},
"pretty": func(data interface{}) string {
p, err := PrettyJson(data)
if err != nil {
return err.Error()
}
return p
},
}
r := os.Getenv("GOPATH")
if r == "" {
r = build.Default.GOPATH
}
t, err := template.New("root").Funcs(fm).ParseGlob(path.Join(r, "src", "github.com", "jackdoe", "baxx", "help", "t", "*.txt"))
if err != nil {
log.Fatal(err)
}
return t
}
var root = Load()
func Render(data HelpObject) string {
var out bytes.Buffer
//root := Load()
if data.Email == "" && data.Status != nil {
data.Email = data.Status.Email
}
err := root.ExecuteTemplate(&out, data.Template.String()+".txt", data)
if err != nil {
panic(err)
}
return out.String()
}