-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
114 lines (95 loc) · 2.63 KB
/
main.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
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/hexdigest/gowrap/generator"
"github.com/pkg/errors"
)
var (
interfaceName = flag.String("i", "", "interface name")
structName = flag.String("s", "", "target struct name, default: <interface name>Tracer")
outputFile = flag.String("o", "", "output filename")
)
const headerTemplate = `
// Code generated by http://github.com/gojuno/tracegen. DO NOT EDIT.
package {{$.Package.Name}}
`
const bodyTemplate = `
import (
opentracing "github.com/opentracing/opentracing-go"
_ext "github.com/opentracing/opentracing-go/ext"
_log "github.com/opentracing/opentracing-go/log"
)
{{ $decorator := (or .Vars.DecoratorName (printf "%sTracer" .Interface.Name)) }}
// {{$decorator}} instruments {{.Interface.Type}} with opentracing spans
type {{$decorator}} struct {
{{.Interface.Type}}
_instance string
}
// New{{$decorator}} returns {{$decorator}}
func New{{$decorator}} (base {{.Interface.Type}}, instance string) {{$decorator}} {
return {{$decorator}} {
{{.Interface.Name}}: base,
_instance: instance,
}
}
{{range $method := .Interface.Methods}}
{{if $method.AcceptsContext}}
// {{$method.Name}} implements {{$.Interface.Type}}
func (_d {{$decorator}}) {{$method.Declaration}} {
_span, ctx := opentracing.StartSpanFromContext(ctx, _d._instance + ".{{$.Interface.Type}}.{{$method.Name}}")
defer func() {
{{if $method.ReturnsError}}if err != nil {
_ext.Error.Set(_span, true)
_span.LogFields(
_log.String("event", "error"),
_log.String("message", err.Error()),
)
}
{{end}}
_span.Finish()
}()
{{$method.Pass (printf "_d.%s." $.Interface.Name) }}
}
{{end}}
{{end}}
`
func main() {
flag.Parse()
if *interfaceName == "" || *outputFile == "" || flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
if *structName == "" {
*structName = fmt.Sprintf("%vTracer", *interfaceName)
}
opts := generator.Options{
InterfaceName: *interfaceName,
SourcePackage: flag.Arg(0),
//SourcePackageAlias: "mm_" + sourcePackage.Name,
HeaderTemplate: headerTemplate,
BodyTemplate: bodyTemplate,
Vars: map[string]interface{}{
"DecoratorName": structName,
},
OutputFile: *outputFile,
}
if err := generate(opts); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
func generate(o generator.Options) error {
g, err := generator.NewGenerator(o)
if err != nil {
return err
}
buf := bytes.NewBuffer([]byte{})
if err = g.Generate(buf); err != nil {
return errors.Wrap(err, "failed to generate decorator")
}
return ioutil.WriteFile(o.OutputFile, buf.Bytes(), 0644)
}