-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplates.go
More file actions
118 lines (97 loc) · 2.34 KB
/
templates.go
File metadata and controls
118 lines (97 loc) · 2.34 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
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 (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
)
type Template struct {
Id string `json:"id"`
Name string `json:"name"`
Event string `json:"event"`
Condition string `json:"condition"`
Template []byte
}
func ParseTemplatesDir(templatesDir string) ([]*Template, error) {
files, err := ioutil.ReadDir(templatesDir)
checkErr(err, "Read templates dir failed:")
templates := []*Template{}
for _, fileInfo := range files {
tmpl, err := parseTemplate(templatesDir, fileInfo)
if err != nil {
log.Println(err.Error())
} else {
templates = append(templates, tmpl)
}
}
return templates, nil
}
func parseTemplate(dir string, file os.FileInfo) (*Template, error) {
var err error
var template *Template
if strings.HasSuffix(file.Name(), "tmpl") {
filePath := fmt.Sprintf("%s/%s", dir, file.Name())
log.Println("Parsing template:", filePath)
file, err := os.Open(filePath)
if err != nil {
log.Println("Error opening template file:", filePath)
return nil, err
}
defer file.Close()
reader := bufio.NewReader(file)
// Read header delimiter of <!--
line, err := reader.ReadString('\n')
if line != "<!--\n" {
return nil, errors.New("Template file didn't begin with <!--")
}
// Read the json config package up until the --> line
config := []byte{}
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
return nil, err
} else {
return nil, errors.New("Invalid template file")
}
}
if string(line) == "-->\n" {
break
}
config = append(config, line...)
}
err = json.Unmarshal(config, &template)
if err != nil {
return nil, errors.New(fmt.Sprintf("Invalid template config: %q", string(config)))
}
if template.Id == "" {
return nil, errors.New(`Template is missing "id" field`)
}
if template.Name == "" {
return nil, errors.New(`Template is missing "name" field`)
}
if template.Event == "" {
return nil, errors.New(`Template is missing "event" field`)
}
// Now store the actual DOM for the template output
dom := []byte{}
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
return nil, err
} else {
break
}
}
dom = append(dom, line...)
}
template.Template = dom
}
return template, err
}