generated from go-uniform/base-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
260 lines (217 loc) · 5.5 KB
/
generator.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//+build generate
//go:generate go run generator.go
package main
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strings"
"text/template"
"encoding/json"
)
const (
blobFileName string = "service/info/meta.go"
embedFolder string = "resources/"
)
var conv = map[string]interface{}{"conv": fmtByteSlice}
var tmpl = template.Must(template.New("").Funcs(conv).Parse(`package info
// Code generated by go generate; DO NOT EDIT.
import "fmt"
type embedBox struct {
storage map[string][]byte
}
// Create new box for embed files
func newEmbedBox() *embedBox {
return &embedBox{storage: make(map[string][]byte)}
}
// Add a file to box
func (e *embedBox) Add(file string, content []byte) {
e.storage[file] = content
}
// Get file's content
// Always use / for looking up
// For example: /init/README.md is actually configs/init/README.md
func (e *embedBox) Get(file string) []byte {
if f, ok := e.storage[file]; ok {
return f
}
return nil
}
// Find for a file
func (e *embedBox) Has(file string) bool {
if _, ok := e.storage[file]; ok {
return true
}
return false
}
// Embed box expose
var box = newEmbedBox()
// Add a file content to box
func Add(file string, content []byte) {
box.Add(file, content)
}
// Get a file from box
func Get(file string) []byte {
return box.Get(file)
}
// Has a file in box
func Has(file string) bool {
return box.Has(file)
}
const (
AppName="{{.Name}}"
AppDescription="{{.Description}}"
AppVersion="{{.Version}}"
AppCommit="{{.Commit}}"
AppRepository="{{.Repository}}"
)
var MustAsset = func(file string) []byte {
var data = box.Get(file)
if data == nil {
panic(fmt.Sprintf("resource '%s' not found", file))
}
return data
}
func init() {
{{- range $name, $file := .Files }}
box.Add("{{ $name }}", []byte{ {{ conv $file }} })
{{- end }}
}`),
)
func fmtByteSlice(s []byte) string {
builder := strings.Builder{}
for _, v := range s {
builder.WriteString(fmt.Sprintf("%d,", int(v)))
}
return builder.String()
}
type TemplateModel struct {
Name string
Description string
Version string
Commit string
Repository string
Files map[string][]byte
}
func main() {
root, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
var name = path.Base(root)
var description = ""
var version = "alpha.dev"
var commit = ""
var repository = ""
tmp, err := exec.Command("git", "remote", "get-url", "origin").Output()
if err == nil && tmp != nil && strings.TrimSpace(string(tmp)) != "" {
repository = strings.TrimSpace(string(tmp))
}
if strings.HasPrefix(repository, "git@github.com:") {
githubRepoInfoUrl := fmt.Sprintf("https://api.github.com/repos/%s", strings.TrimPrefix(strings.TrimSuffix(repository, ".git"), "git@github.com:"))
request, err := http.NewRequest("GET", githubRepoInfoUrl, nil)
client := &http.Client{}
resp, err := client.Do(request)
if err == nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
var object map[string]interface{}
if json.Unmarshal(body, &object) == nil {
if value, exists := object["description"]; exists {
description = fmt.Sprint(value)
}
}
}
}
}
tmp, err = ioutil.ReadFile(".description")
if err == nil {
description = string(tmp)
}
hostname, err := os.Hostname()
if err == nil {
me, err := user.Current()
if err == nil && me != nil {
commit = fmt.Sprintf("%s@%s", me.Username, hostname)
}
}
tmp, err = exec.Command("git", "rev-parse", "--short", "HEAD").Output()
if err == nil && tmp != nil {
commit = strings.TrimSpace(string(tmp))
version = fmt.Sprintf("%s.dev", commit)
tmp, err = exec.Command("git", "tag", "--points-at", "HEAD").Output()
if err == nil && tmp != nil && strings.TrimSpace(string(tmp)) != "" {
version = strings.TrimSpace(string(tmp))
}
}
// Checking directory with files
if _, err := os.Stat(embedFolder); os.IsNotExist(err) {
log.Fatal("Static directory does not exists!")
}
// Create map for filenames
configs := TemplateModel{
Name: name,
Description: description,
Version: version,
Commit: commit,
Repository: repository,
Files: make(map[string][]byte),
}
// Walking through embed directory
err = filepath.Walk(embedFolder, func(path string, info os.FileInfo, err error) error {
relativePath := filepath.ToSlash(strings.TrimPrefix(path, embedFolder))
if info.IsDir() {
// Skip directories
log.Println(path, "is a directory, skipping...")
return nil
} else {
// If element is a simple file, embed
log.Println(path, "is a file, packing in...")
b, err := ioutil.ReadFile(path)
if err != nil {
// If file not reading
log.Printf("Error reading %s: %s", path, err)
return err
}
// Add file name to map
configs.Files[relativePath] = b
}
return nil
})
if err != nil {
log.Fatal("Error walking through embed directory:", err)
}
makeBlobFile(configs)
}
func makeBlobFile(configs TemplateModel) {
// Create blob file
f, err := os.Create(blobFileName)
if err != nil {
log.Fatal("Error creating blob file:", err)
}
defer f.Close()
// Create buffer
builder := &bytes.Buffer{}
// Execute template
if err = tmpl.Execute(builder, configs); err != nil {
log.Fatal("Error executing template", err)
}
// Formatting generated code
data, err := format.Source(builder.Bytes())
if err != nil {
log.Fatal("Error formatting generated code", err)
}
// Writing blob file
if err = ioutil.WriteFile(blobFileName, data, os.ModePerm); err != nil {
log.Fatal("Error writing blob file", err)
}
}