-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert_context.go
79 lines (61 loc) · 1.07 KB
/
insert_context.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
package main
import (
"github.com/ZhengHe-MD/gorefactor"
"github.com/dave/dst"
"log"
"os"
)
/*
say we want to refactor the following code
==================================
package main
func f() {}
func main() {
f()
f()
}
==================================
to
==================================
package main
import "context"
func f(ctx context.Context) {}
func main() {
f(context.TODO())
f(context.TODO())
}
==================================
*/
func main() {
var src = `
package main
func f() {}
func main() {
f()
f()
}
`
df, err := gorefactor.ParseSrcFileFromBytes([]byte(src))
if err != nil {
log.Println(err)
return
}
gorefactor.AddFieldToFuncDeclParams(df, "f", &dst.Field{
Names: []*dst.Ident{dst.NewIdent("ctx")},
Type: &dst.Ident{
Name: "Context",
Path: "context",
},
}, 0)
gorefactor.AddArgToCallExpr(df, gorefactor.EmptyScope, "f", &dst.CallExpr{
Fun: &dst.Ident{
Name: "TODO",
Path: "context",
},
}, 0)
err = gorefactor.FprintFile(os.Stdout, df)
if err != nil {
log.Println(err)
return
}
}