This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
iwanta.go
199 lines (168 loc) · 4.71 KB
/
iwanta.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
package gutowire
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"github.com/stoewer/go-strcase"
)
const (
thisIsYourTemplate = `
func thisIsYour%s(res *%s,%s) (err error, cleanup func()) {
*res, cleanup, err = %s
return
}
`
)
var regexpCall = regexp.MustCompile(`gutowire\.IWantA\(&([a-zA-Z]+).*?\)`)
type iwantA struct {
wantInputIdent string
wantName string
thisIsYourFuncName string
callFileLines []string
callLine int
callFile string
}
func (iw *iwantA) initWantArgIdent() {
callLineStr := regexpCall.FindAllStringSubmatch(strings.TrimSpace(iw.callFileLines[iw.callLine-1]), -1)
for i := range callLineStr {
if len(callLineStr[i]) == 2 {
iw.wantInputIdent = callLineStr[i][1]
break
}
}
// rewrite caller replace IWantA with thisIsYour
if iw.wantInputIdent == "" {
iw.wantInputIdent = "nil"
} else {
iw.wantInputIdent = "&" + iw.wantInputIdent
}
}
func IWantA(in interface{}, searchDepDirs ...string) (_ struct{}) {
if len(searchDepDirs) == 0 {
modPath := getGoModDir()
if len(modPath) > 0 {
searchDepDirs = append(searchDepDirs, modPath)
}
}
_, callFile, callLine, ok := runtime.Caller(1)
if !ok {
panic("error call path")
}
var (
callFileData, _ = ioutil.ReadFile(callFile)
iw = &iwantA{
callFile: callFile,
callLine: callLine,
callFileLines: strings.Split(string(callFileData), "\n"),
}
)
iw.initWantArgIdent()
// gen wire.go
var (
wantTypeVar string
genSuccess bool
rType = reflect.TypeOf(in).Elem()
modeBase, _ = getModBase()
callPkgPath = getPkgPath(callFile, modeBase)
)
if rType.PkgPath() == callPkgPath {
wantTypeVar = rType.Name()
} else {
wantTypeVar = rType.String()
}
var (
wantTypeName = strcase.SnakeCase(strings.Replace(strings.Replace(wantTypeVar, "_", "", -1), ".", "_", -1))
genPath = filepath.Dir(callFile)
wireOpt = make([]Option, 0)
)
iw.thisIsYourFuncName = strcase.UpperCamelCase(wantTypeName)
// clean tmp
defer func() {
iw.cleanIWantATemp(callFile)
if genSuccess {
os.Exit(0)
}
}()
for _, s := range searchDepDirs {
wireOpt = append(wireOpt, WithSearchPath(s))
}
wireOpt = append(wireOpt, InitStruct(strings.TrimPrefix(wantTypeVar, "*")))
// run autowire
if err := RunAutoWire(genPath, wireOpt...); err != nil {
panic(err)
}
// gen init
args, err := iw.writeInitFile(wantTypeVar, wantTypeName)
if err != nil {
panic(err)
}
if err = iw.updateCallFile(args); err != nil {
panic(err)
}
genSuccess = true
return struct{}{}
}
func (iw *iwantA) updateCallFile(configArgs []string) (err error) {
callLine := strings.TrimSpace(iw.callFileLines[iw.callLine-1])
callArgs := strings.Join(append([]string{iw.wantInputIdent}, configArgs...), ",")
assignStr := fmt.Sprintf("_, _ = thisIsYour%s(%s)", iw.thisIsYourFuncName, callArgs)
if strings.HasPrefix(callLine, "var ") {
assignStr = "var " + assignStr
}
iw.callFileLines[iw.callLine-1] = "// " + callLine
iw.callFileLines = append(iw.callFileLines[:iw.callLine], append([]string{assignStr}, iw.callFileLines[iw.callLine:]...)...)
return importAndWrite(iw.callFile, []byte(strings.Join(iw.callFileLines, "\n")))
}
var regexpInitMethod = regexp.MustCompile(`Initialize(.+?)\((.*?)\)`)
func (iw *iwantA) writeInitFile(wantVar, name string) (args []string, err error) {
genPath := filepath.Dir(iw.callFile)
initFileData, err := ioutil.ReadFile(filepath.Join(genPath, "wire_gen.go"))
if err != nil {
return
}
call := ""
ret := regexpInitMethod.FindStringSubmatch(string(initFileData))
if len(ret) >= 2 {
argsVar := make([]string, 0)
if len(ret) > 2 {
for _, sp := range strings.Split(ret[2], ",") {
if spp := strings.SplitN(sp, " ", 2); len(spp) == 2 {
args = append(args, "&"+strings.TrimPrefix(spp[1], "*")+"{}")
argsVar = append(argsVar, spp[0])
}
}
}
call = fmt.Sprintf(`Initialize%s(%s)`, ret[1], strings.Join(argsVar, ","))
} else {
err = errors.New("invalid init file")
return
}
filename := fmt.Sprintf("%s_init", strcase.SnakeCase(name))
if strings.HasSuffix(iw.callFile, "_test.go") {
filename += "_test"
}
filename += ".go"
initFileData = append(initFileData, fmt.Sprintf(thisIsYourTemplate, iw.thisIsYourFuncName, wantVar, ret[2], call)...)
initFileName := filepath.Join(genPath, filename)
if err = importAndWrite(initFileName, initFileData); err != nil {
return
}
return
}
func (iw *iwantA) cleanIWantATemp(f string) {
dir := filepath.Dir(f)
infos, _ := ioutil.ReadDir(dir)
for _, info := range infos {
if strings.HasPrefix(info.Name(), "autowire") ||
info.Name() == "wire.gen.go" ||
info.Name() == "wire_gen.go" {
_ = os.Remove(filepath.Join(dir, info.Name()))
}
}
}