This repository has been archived by the owner on May 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
templates.go
118 lines (105 loc) · 2.47 KB
/
templates.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"bytes"
"fmt"
"log"
"math"
"net/url"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/dustin/go-humanize"
)
var (
compactNumUnits = []string{"", "k", "M"}
tplFuncMap = template.FuncMap{
// The name "title" is what the function will be called in the template text.
"color": func(num int) string {
return string(runeIrcColor) + strconv.Itoa(num)
},
"bcolor": func(fgNum, bgNum int) string {
return string(runeIrcColor) + strconv.Itoa(fgNum) + "," + strconv.Itoa(bgNum)
},
"bold": func() string {
return string(runeIrcBold)
},
"italic": func() string {
return string(runeIrcItalic)
},
"reset": func() string {
return string(runeIrcReset) + string(runeIrcColor)
},
"reverse": func() string {
return string(runeIrcReverse)
},
"underline": func() string {
return string(runeIrcUnderline)
},
"urlencode": func(s string) string {
return url.QueryEscape(s)
},
"yesno": func(yes string, no string, value bool) string {
if value {
return yes
}
return no
},
"excerpt": func(maxLength uint16, text string) string {
if len(text) > int(maxLength) {
return text[0:maxLength-1] + "\u2026"
}
return text
},
"comma": func(num uint64) string {
return humanize.Comma(int64(num))
},
"compactnum": func(num uint64) string {
// 1 => 0
// 1000 => 1
// 1000000 => 2
log10 := math.Floor(math.Log10(float64(num)) / 3)
// Cut to available units
cut := int(math.Min(float64(len(compactNumUnits)-1), log10))
numf := float64(num)
numf /= math.Pow10(cut * 3)
// Rounding
numf = math.Floor((numf*10)+.5) / 10
if numf >= 1000 {
numf /= 1000
if cut < len(compactNumUnits)-1 {
cut++
}
}
unit := compactNumUnits[cut]
f := "%.1f%s"
if numf-math.Floor(numf) < 0.05 {
f = "%.0f%s"
}
return fmt.Sprintf(f, numf, unit)
},
"ago": func(t time.Time) string {
return humanize.Time(t)
},
"size": func(s uint64) string {
return humanize.Bytes(s)
},
}
ircTpl = template.Must(
template.New("").
Funcs(tplFuncMap).
ParseGlob("*.tpl"))
rxInsignificantWhitespace = regexp.MustCompile(`\s+`)
)
func tplString(name string, data interface{}) (string, error) {
w := new(bytes.Buffer)
if err := ircTpl.ExecuteTemplate(w, name, data); err != nil {
return "", err
}
s := w.String()
s = rxInsignificantWhitespace.ReplaceAllString(s, " ")
s = strings.Trim(s, " ")
log.Printf("tplString(%v): %s", name, s)
return s, nil
}