-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·178 lines (142 loc) · 3.55 KB
/
main.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
)
// Extension is the required file extension for processed files.
const Extension = ".tmpl"
func main() {
t := &Tmpl{}
if err := t.Process(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if err := t.Compile(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// Tmpl represents a template compiler.
type Tmpl struct {
// Files to be processed.
Paths []string
// Data to be applied to the files during generation.
Data interface{}
}
// Process parses the command line flags from args.
func (t *Tmpl) Process(args []string) (err error) {
flg := flag.NewFlagSet("tmpl", flag.ContinueOnError)
data := flg.String("data", "", "Provide template data using json")
file := flg.String("file", "", "Provide template data using a file path")
flg.SetOutput(os.Stderr)
// Parse the command line arguments.
if err = flg.Parse(args); err != nil {
return err
}
if *data != "" {
if err = json.Unmarshal([]byte(*data), &t.Data); err != nil {
return fmt.Errorf("Problem parsing data %s", *data)
}
}
if *file != "" {
var buf []byte
if buf, err = ioutil.ReadFile(*file); err != nil {
return fmt.Errorf("Problem reading file %s", *file)
}
if err = json.Unmarshal(buf, &t.Data); err != nil {
return fmt.Errorf("Problem parsing file %s", *file)
}
}
// Use arguments as filepaths.
t.Paths = flg.Args()
return nil
}
// Compile compiles and generates the template files.
func (t *Tmpl) Compile() (err error) {
// Verify we have at least one path.
if len(t.Paths) == 0 {
return errors.New("Provide a file path.")
}
// Process and compile each path.
for _, path := range t.Paths {
if err = t.compile(path); err != nil {
return err
}
}
return nil
}
func (t *Tmpl) compile(path string) error {
// Validate that we have a prefix we can strip off for the generated path.
if !strings.HasSuffix(path, Extension) {
return fmt.Errorf("File %s must have extension %s extension", path, Extension)
}
file := strings.TrimSuffix(path, Extension)
// Stat the file to retrieve the mode.
fil, err := os.Stat(path)
if os.IsNotExist(err) {
return fmt.Errorf("File %s not found", path)
} else if err != nil {
return err
}
// Read in template file.
src, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return fmt.Errorf("File %s not found", path)
} else if err != nil {
return err
}
// Parse file into template.
tpl, err := template.New("main").Funcs(functions).Parse(string(src))
if err != nil {
return err
}
// Comment the generated code.
var buf bytes.Buffer
switch filepath.Ext(file) {
case ".go":
fmt.Fprintln(&buf, "// Code generated by https://github.com/abcum/tmpl")
fmt.Fprintln(&buf, "// Source file:", path)
fmt.Fprintln(&buf, "// DO NOT EDIT!")
fmt.Fprintln(&buf, "")
}
// Execute the template.
if err := tpl.Execute(&buf, t.Data); err != nil {
return err
}
// Get the generated code.
output := buf.Bytes()
// Format any golang code.
switch filepath.Ext(file) {
case ".go":
formatted, err := format.Source(output)
if err != nil {
return err
}
output = formatted
}
// Write buffer to file.
if err := ioutil.WriteFile(file, output, fil.Mode()); err != nil {
return err
}
return nil
}
var functions = template.FuncMap{
"upcase": strings.ToUpper,
"downcase": strings.ToLower,
"camel": camelCase,
}
func camelCase(s string) string {
if s == "" {
return s
}
return strings.ToLower(string(s[0])) + s[1:]
}