forked from naoina/kocha
/
util.go
465 lines (425 loc) · 10.6 KB
/
util.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package kocha
import (
"bufio"
"bytes"
"compress/gzip"
"fmt"
htmltemplate "html/template"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"go/build"
"go/format"
"github.com/daviddengcn/go-colortext"
)
var (
// Now returns current time. This is for mock in tests.
Now = func() time.Time { return time.Now() }
// for test.
ImportDir = build.ImportDir
)
// ToCamelCase returns a copy of the string s with all Unicode letters mapped to their camel case.
// It will convert to upper case previous letter of '_' and first letter, and remove letter of '_'.
func ToCamelCase(s string) string {
if s == "" {
return ""
}
result := make([]rune, 0, len(s))
upper := false
for _, r := range s {
if r == '_' {
upper = true
continue
}
if upper {
result = append(result, unicode.ToUpper(r))
upper = false
continue
}
result = append(result, r)
}
result[0] = unicode.ToUpper(result[0])
return string(result)
}
// ToSnakeCase returns a copy of the string s with all Unicode letters mapped to their snake case.
// It will insert letter of '_' at position of previous letter of uppercase and all
// letters convert to lower case.
func ToSnakeCase(s string) string {
if s == "" {
return ""
}
var result bytes.Buffer
result.WriteRune(unicode.ToLower(rune(s[0])))
for _, c := range s[1:] {
if unicode.IsUpper(c) {
result.WriteRune('_')
}
result.WriteRune(unicode.ToLower(c))
}
return result.String()
}
// SplitExt returns pair of file name and extension.
//
// It will truncated a dot of extension.
// e.g. When the given path is "path/to/image.png", SplitExt returns ("path/to/image", "png").
func SplitExt(path string) (name, ext string) {
for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
if path[i] == '.' {
return path[:i], path[i+1:]
}
}
return path, ""
}
func normPath(p string) string {
result := path.Clean(p)
// path.Clean() truncate the trailing slash but add it.
if p[len(p)-1] == '/' && result != "/" {
result += "/"
}
return result
}
type Error struct {
Usager usager
Message string
}
func (e Error) Error() string {
return e.Message
}
type usager interface {
Usage() string
}
type fileStatus uint8
const (
fileStatusConflict fileStatus = iota
fileStatusNoConflict
fileStatusIdentical
)
func PanicOnError(usager usager, format string, a ...interface{}) {
panic(Error{usager, fmt.Sprintf(format, a...)})
}
func CopyTemplate(u usager, srcPath, dstPath string, data map[string]interface{}) {
tmpl, err := template.ParseFiles(srcPath)
if err != nil {
PanicOnError(u, "abort: failed to parse template: %v: %v", srcPath, err)
}
var bufFrom bytes.Buffer
if err := tmpl.Execute(&bufFrom, data); err != nil {
PanicOnError(u, "abort: failed to process template: %v: %v", srcPath, err)
}
buf := bufFrom.Bytes()
if strings.HasSuffix(srcPath, ".go.template") {
if buf, err = format.Source(buf); err != nil {
PanicOnError(u, "abort: failed to gofmt: %v: %v", srcPath, err)
}
}
dstDir := filepath.Dir(dstPath)
if _, err := os.Stat(dstDir); os.IsNotExist(err) {
PrintCreateDirectory(dstDir)
if err := os.MkdirAll(dstDir, 0755); err != nil {
PanicOnError(u, "abort: failed to create directory: %v: %v", dstDir, err)
}
}
printFunc := PrintCreate
switch detectConflict(u, buf, dstPath) {
case fileStatusConflict:
PrintConflict(dstPath)
if !confirmOverwrite(dstPath) {
PrintSkip(dstPath)
return
}
printFunc = PrintOverwrite
case fileStatusIdentical:
PrintIdentical(dstPath)
return
}
dstFile, err := os.Create(dstPath)
if err != nil {
PanicOnError(u, "abort: failed to create file: %v: %v", dstPath, err)
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, bytes.NewBuffer(buf)); err != nil {
PanicOnError(u, "abort: failed to output file: %v: %v", dstPath, err)
}
printFunc(dstPath)
}
func detectConflict(u usager, src []byte, dstPath string) fileStatus {
if _, err := os.Stat(dstPath); os.IsNotExist(err) {
return fileStatusNoConflict
}
dstBuf, err := ioutil.ReadFile(dstPath)
if err != nil {
PanicOnError(u, "abort: failed to read file: %v", err)
}
if bytes.Equal(src, dstBuf) {
return fileStatusIdentical
}
return fileStatusConflict
}
func confirmOverwrite(dstPath string) bool {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("Overwrite %v? [Yn] ", dstPath)
yesno, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
switch strings.ToUpper(strings.TrimSpace(yesno)) {
case "", "YES", "Y":
return true
case "NO", "N":
return false
}
}
}
func PrintRed(s string, a ...interface{}) {
printColor(ct.Red, s, a...)
}
func PrintGreen(s string, a ...interface{}) {
printColor(ct.Green, s, a...)
}
func PrintYellow(s string, a ...interface{}) {
printColor(ct.Yellow, s, a...)
}
func PrintBlue(s string, a ...interface{}) {
printColor(ct.Blue, s, a...)
}
func PrintMagenta(s string, a ...interface{}) {
printColor(ct.Magenta, s, a...)
}
func PrintCyan(s string, a ...interface{}) {
printColor(ct.Cyan, s, a...)
}
func printColor(color ct.Color, format string, a ...interface{}) {
ct.ChangeColor(color, true, ct.None, false)
fmt.Printf(format, a...)
ct.ResetColor()
}
func PrintIdentical(path string) {
printPathStatus(ct.Blue, "identical", path)
}
func PrintConflict(path string) {
printPathStatus(ct.Red, "conflict", path)
}
func PrintSkip(path string) {
printPathStatus(ct.Cyan, "skip", path)
}
func PrintOverwrite(path string) {
printPathStatus(ct.Cyan, "overwrite", path)
}
func PrintCreate(path string) {
printPathStatus(ct.Green, "create", path)
}
func PrintExist(path string) {
printPathStatus(ct.Blue, "exist", path)
}
func PrintCreateDirectory(path string) {
printPathStatus(ct.Green, "create directory", path)
}
func printPathStatus(color ct.Color, message, s string) {
printColor(color, "%20s", message)
fmt.Println("", s)
}
// GoString returns Go-syntax representation of the value.
// It returns compilable Go-syntax that different with "%#v" format for fmt package.
func GoString(i interface{}) string {
switch t := i.(type) {
case *regexp.Regexp:
return fmt.Sprintf(`regexp.MustCompile(%q)`, t)
case *htmltemplate.Template:
var buf bytes.Buffer
for _, t := range t.Templates() {
if t.Name() == "content" {
continue
}
if _, err := buf.WriteString(reflect.ValueOf(t).Elem().FieldByName("text").Elem().FieldByName("text").String()); err != nil {
panic(err)
}
}
return fmt.Sprintf(`template.Must(template.New(%q).Funcs(kocha.TemplateFuncs).Parse(kocha.Gunzip(%q)))`, t.Name(), Gzip(buf.String()))
case fmt.GoStringer:
return t.GoString()
case nil:
return "nil"
}
v := reflect.ValueOf(i)
var name string
if v.Kind() == reflect.Ptr {
if v = v.Elem(); !v.IsValid() {
return "nil"
}
name = "&"
}
name += v.Type().String()
var (
tmplStr string
fields interface{}
)
switch v.Kind() {
case reflect.Struct:
f := make(map[string]interface{})
for i := 0; i < v.NumField(); i++ {
if tf := v.Type().Field(i); !tf.Anonymous && v.Field(i).CanInterface() {
f[tf.Name] = GoString(v.Field(i).Interface())
}
}
tmplStr = `
{{.name}}{
{{range $name, $value := .fields}}
{{$name}}: {{$value}},
{{end}}
}`
fields = f
case reflect.Slice:
f := make([]string, v.Len())
for i := 0; i < v.Len(); i++ {
f[i] = GoString(v.Index(i).Interface())
}
tmplStr = `
{{.name}}{
{{range $value := .fields}}
{{$value}},
{{end}}
}`
fields = f
case reflect.Map:
f := make(map[interface{}]interface{})
for _, k := range v.MapKeys() {
f[k.Interface()] = GoString(v.MapIndex(k).Interface())
}
tmplStr = `
{{.name}}{
{{range $name, $value := .fields}}
{{$name|printf "%q"}}: {{$value}},
{{end}}
}`
fields = f
default:
return fmt.Sprintf("%#v", v.Interface())
}
t := template.Must(template.New(name).Parse(tmplStr))
var buf bytes.Buffer
if err := t.Execute(&buf, map[string]interface{}{
"name": name,
"fields": fields,
}); err != nil {
panic(err)
}
return buf.String()
}
// Gzip returns gzipped string.
func Gzip(raw string) string {
var gzipped bytes.Buffer
w, err := gzip.NewWriterLevel(&gzipped, gzip.BestCompression)
if err != nil {
panic(err)
}
if _, err := w.Write([]byte(raw)); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
return gzipped.String()
}
// Gunzip returns unzipped string.
func Gunzip(gz string) string {
r, err := gzip.NewReader(bytes.NewReader([]byte(gz)))
if err != nil {
panic(err)
}
result, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
return string(result)
}
func detectContentType(r io.Reader) (contentType string) {
buf := make([]byte, 512)
if n, err := io.ReadFull(r, buf); err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
panic(err)
}
buf = buf[:n]
}
if rs, ok := r.(io.Seeker); ok {
if _, err := rs.Seek(0, os.SEEK_SET); err != nil {
panic(err)
}
}
return http.DetectContentType(buf)
}
var settingEnvRegexp = regexp.MustCompile(`\bkocha\.SettingEnv\(\s*(.+?)\s*,\s*(.+?)\s*\)`)
// FindSettingEnv returns map of environment variables.
// Key of map is key of environment variable, Value of map is value of
// environment variable.
func FindSettingEnv() (map[string]string, error) {
pwd, err := os.Getwd()
if err != nil {
return nil, err
}
env := make(map[string]string)
if err := filepath.Walk(pwd, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
switch info.Name()[0] {
case '.', '_':
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
body, err := ioutil.ReadFile(path)
if err != nil {
return err
}
matches := settingEnvRegexp.FindAllStringSubmatch(string(body), -1)
if matches == nil {
return nil
}
for _, m := range matches {
key, err := strconv.Unquote(m[1])
if err != nil {
continue
}
value, err := strconv.Unquote(m[2])
if err != nil {
value = "WILL BE SET IN RUNTIME"
}
env[key] = value
}
return nil
}); err != nil {
return nil, err
}
return env, nil
}
// FindAppDir returns application directory. (aka import path)
// An application directory retrieves from current working directory.
// For example, if current working directory is
// "/path/to/gopath/src/github.com/naoina/myapp", FindAppDir returns
// "github.com/naoina/myapp".
func FindAppDir() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
dstBasePath := filepath.Join(filepath.SplitList(build.Default.GOPATH)[0], "src")
return filepath.ToSlash(dir)[len(dstBasePath)+1:], nil
}