MCPcopy Create free account
hub / github.com/divan/gotrace / addCode

Function addCode

rewrite.go:47–97  ·  view source on GitHub ↗

addCode searches for main func in data, and updates AST code adding tracing functions.

(path string)

Source from the content-addressed store, hash-verified

45// addCode searches for main func in data, and updates AST code
46// adding tracing functions.
47func addCode(path string) ([]byte, error) {
48 var conf loader.Config
49 if _, err := conf.FromArgs([]string{path}, false); err != nil {
50 return nil, err
51 }
52
53 prog, err := conf.Load()
54 if err != nil {
55 return nil, err
56 }
57
58 // check if runtime/trace already imported
59 for i, _ := range prog.Imported {
60 if i == "runtime/trace" {
61 return nil, ErrImported
62 }
63 }
64
65 pkg := prog.Created[0]
66
67 // TODO: find file with main func inside
68 astFile := pkg.Files[0]
69
70 // add imports
71 astutil.AddImport(prog.Fset, astFile, "os")
72 astutil.AddImport(prog.Fset, astFile, "runtime/trace")
73 astutil.AddImport(prog.Fset, astFile, "time")
74
75 // add start/stop code
76 ast.Inspect(astFile, func(n ast.Node) bool {
77 switch x := n.(type) {
78 case *ast.FuncDecl:
79 // find 'main' function
80 if x.Name.Name == "main" && x.Recv == nil {
81 stmts := createTraceStmts()
82 stmts = append(stmts, x.Body.List...)
83 x.Body.List = stmts
84 return true
85 }
86 }
87 return true
88 })
89
90 var buf bytes.Buffer
91 err = printer.Fprint(&buf, prog.Fset, astFile)
92 if err != nil {
93 return nil, err
94 }
95
96 return buf.Bytes(), nil
97}
98
99func createTraceStmts() []ast.Stmt {
100 ret := make([]ast.Stmt, 2)

Callers 1

rewriteSourceFunction · 0.85

Calls 1

createTraceStmtsFunction · 0.85

Tested by

no test coverage detected