-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathmain.go
246 lines (213 loc) · 4.92 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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"errors"
"flag"
"fmt"
"go/token"
"go/types"
"log"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"golang.org/x/tools/go/packages"
)
type arrFlags []string
const outputFileName = "output.proto"
func (i *arrFlags) String() string {
return ""
}
func (i *arrFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
var (
filter = flag.String("filter", "", "Filter by struct names. Case insensitive.")
targetFolder = flag.String("f", ".", "Protobuf output file path.")
pkgFlags arrFlags
)
func main() {
flag.Var(&pkgFlags, "p", `Fully qualified path of packages to analyse. Relative paths ("./example/in") are allowed.`)
flag.Parse()
pwd, err := os.Getwd()
if err != nil {
log.Fatalf("error getting working directory: %s", err)
}
if len(pkgFlags) == 0 {
flag.PrintDefaults()
os.Exit(1)
}
//ensure the path exists
_, err = os.Stat(*targetFolder)
if err != nil {
log.Fatalf("error getting output file: %s", err)
}
pkgs, err := loadPackages(pwd, pkgFlags)
if err != nil {
log.Fatalf("error fetching packages: %s", err)
}
msgs := getMessages(pkgs, strings.ToLower(*filter))
if err = writeOutput(msgs, *targetFolder); err != nil {
log.Fatalf("error writing output: %s", err)
}
log.Printf("output file written to %s%s%s\n", pwd, string(os.PathSeparator), outputFileName)
}
// attempt to load all packages
func loadPackages(pwd string, pkgs []string) ([]*packages.Package, error) {
fset := token.NewFileSet()
cfg := &packages.Config{
Dir: pwd,
Mode: packages.LoadSyntax,
Fset: fset,
}
packages, err := packages.Load(cfg, pkgs...)
if err != nil {
return nil, err
}
var errs = ""
//check each loaded package for errors during loading
for _, p := range packages {
if len(p.Errors) > 0 {
errs += fmt.Sprintf("error fetching package %s: ", p.String())
for _, e := range p.Errors {
errs += e.Error()
}
errs += "; "
}
}
if errs != "" {
return nil, errors.New(errs)
}
return packages, nil
}
type message struct {
Name string
Fields []*field
}
type field struct {
Name string
TypeName string
Order int
IsRepeated bool
}
func getMessages(pkgs []*packages.Package, filter string) []*message {
var out []*message
seen := map[string]struct{}{}
for _, p := range pkgs {
for _, t := range p.TypesInfo.Defs {
if t == nil {
continue
}
if !t.Exported() {
continue
}
if _, ok := seen[t.Name()]; ok {
continue
}
if s, ok := t.Type().Underlying().(*types.Struct); ok {
seen[t.Name()] = struct{}{}
if filter == "" || strings.Contains(strings.ToLower(t.Name()), filter) {
out = appendMessage(out, t, s)
}
}
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
func appendMessage(out []*message, t types.Object, s *types.Struct) []*message {
msg := &message{
Name: t.Name(),
Fields: []*field{},
}
for i := 0; i < s.NumFields(); i++ {
f := s.Field(i)
if !f.Exported() {
continue
}
newField := &field{
Name: toProtoFieldName(f.Name()),
TypeName: toProtoFieldTypeName(f),
IsRepeated: isRepeated(f),
Order: i + 1,
}
msg.Fields = append(msg.Fields, newField)
}
out = append(out, msg)
return out
}
func toProtoFieldTypeName(f *types.Var) string {
switch f.Type().Underlying().(type) {
case *types.Basic:
name := f.Type().String()
return normalizeType(name)
case *types.Slice:
name := splitNameHelper(f)
return normalizeType(strings.TrimLeft(name, "[]"))
case *types.Pointer, *types.Struct:
name := splitNameHelper(f)
return normalizeType(name)
}
return f.Type().String()
}
func splitNameHelper(f *types.Var) string {
// TODO: this is ugly. Find another way of getting field type name.
parts := strings.Split(f.Type().String(), ".")
name := parts[len(parts)-1]
if name[0] == '*' {
name = name[1:]
}
return name
}
func normalizeType(name string) string {
switch name {
case "int":
return "int64"
case "float32":
return "float"
case "float64":
return "double"
default:
return name
}
}
func isRepeated(f *types.Var) bool {
_, ok := f.Type().Underlying().(*types.Slice)
return ok
}
func toProtoFieldName(name string) string {
if len(name) == 2 {
return strings.ToLower(name)
}
r, n := utf8.DecodeRuneInString(name)
return string(unicode.ToLower(r)) + name[n:]
}
func writeOutput(msgs []*message, path string) error {
msgTemplate := `syntax = "proto3";
package proto;
{{range .}}
message {{.Name}} {
{{- range .Fields}}
{{- if .IsRepeated}}
repeated {{.TypeName}} {{.Name}} = {{.Order}};
{{- else}}
{{.TypeName}} {{.Name}} = {{.Order}};
{{- end}}
{{- end}}
}
{{end}}
`
tmpl, err := template.New("test").Parse(msgTemplate)
if err != nil {
panic(err)
}
f, err := os.Create(filepath.Join(path, outputFileName))
if err != nil {
return fmt.Errorf("unable to create file %s : %s", outputFileName, err)
}
defer f.Close()
return tmpl.Execute(f, msgs)
}