aboutsummaryrefslogtreecommitdiff
path: root/template.go
blob: bb8d5020633d21695dca5300b57d0142e3c34ab3 (plain)
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
package main

import (
	"errors"
	html "html/template"
	"io"
	"os"
	"strings"
	text "text/template"
)

type Templater interface {
	Execute(wr io.Writer, data any) error
}

var (
	templateFunc = map[string]any{
		"DerefI": func(i *int) int { return *i },
		"DerefS": func(i *string) string { return *i },
		"Format": func(e *Entry, format string) string {
			p := e.Properties()
			p["commit"] = strings.Replace(*e.Commit, "-dirty", "", -1)
			return tsprintf(format, p)
		},
	}
)

func GetTemplate(templateType, filePath string) (Templater, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}

	tmpl, err := io.ReadAll(file)
	if err != nil {
		return nil, err
	}

	switch templateType {
	case "text":
		return text.New("text").
			Funcs(templateFunc).
			Parse(string(tmpl))
	case "html":
		return html.New("html").
			Funcs(templateFunc).
			Parse(string(tmpl))
	default:
		return nil, errors.New("Invalid template type")
	}
}

func tsprintf(format string, params map[string]string) string {
	for key, val := range params {
		format = strings.Replace(format, "%{"+key+"}s", val, -1)
	}
	return format
}