forked from BWMuller/apig
/
skeleton.go
113 lines (93 loc) · 2.08 KB
/
skeleton.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
package apig
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"text/template"
"github.com/danysz/apig/msg"
"github.com/danysz/apig/util"
)
var r = regexp.MustCompile(`_templates/skeleton/.*\.tmpl$`)
func generateSkeleton(detail *Detail, outDir string) error {
var wg sync.WaitGroup
errCh := make(chan error, 1)
done := make(chan bool, 1)
for _, skeleton := range AssetNames() {
wg.Add(1)
go func(s string) {
defer wg.Done()
if !r.MatchString(s) {
return
}
trim := strings.Replace(s, "_templates/skeleton/", "", 1)
path := strings.Replace(trim, ".tmpl", "", 1)
dstPath := filepath.Join(outDir, path)
body, err := Asset(s)
if err != nil {
errCh <- err
}
tmpl, err := template.New("complex").Parse(string(body))
if err != nil {
errCh <- err
}
var buf bytes.Buffer
var src []byte
if err := tmpl.Execute(&buf, detail); err != nil {
errCh <- err
}
if strings.HasSuffix(path, ".go") {
src, err = format.Source(buf.Bytes())
if err != nil {
errCh <- err
}
} else {
src = buf.Bytes()
}
if !util.FileExists(filepath.Dir(dstPath)) {
if err := util.Mkdir(filepath.Dir(dstPath)); err != nil {
errCh <- err
}
}
if err := ioutil.WriteFile(dstPath, src, 0644); err != nil {
errCh <- err
}
msg.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)
}(skeleton)
}
wg.Wait()
close(done)
select {
case <-done:
case err := <-errCh:
if err != nil {
return err
}
}
return nil
}
func Skeleton(gopath, vcs, username, project, namespace, database string) int {
detail := &Detail{
VCS: vcs,
User: username,
Project: project,
Namespace: namespace,
Database: database,
}
outDir := filepath.Join(gopath, "src", detail.VCS, detail.User, detail.Project)
if util.FileExists(outDir) {
fmt.Fprintf(os.Stderr, "%s is already exists", outDir)
return 1
}
if err := generateSkeleton(detail, outDir); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
msg.Printf("===> Created %s", outDir)
return 0
}