-
Notifications
You must be signed in to change notification settings - Fork 5
/
gen_thrift.go
117 lines (94 loc) · 2.55 KB
/
gen_thrift.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
package main
import (
"flag"
"fmt"
"io"
"regexp"
"sort"
"strings"
)
var (
flagThriftNS = flag.String("thriftns", "go schema,py schema", "set comma separated list of thrift namespaces")
)
var thriftPublicTypeRegexp = regexp.MustCompile("[0-9A-Za-z]+")
func thriftPublicType(name string) string {
parts := thriftPublicTypeRegexp.FindAllString(name, -1)
return strings.Join(parts, "_")
}
//var thriftPublicType = goPublicType
var thriftTypeConv = typeConv{
"boolean": "bool",
"number": "double",
"string": "string",
}
var thriftReservedWords = map[string]string{
"package": "_package",
}
// GenThrift generates thrift spec to w.
func GenThrift(w io.Writer, jsonSchemaURL string) error {
list, err := ParseSchema(jsonSchemaURL)
if err != nil {
return err
}
fmt.Fprintf(w, "// This thrift spec was auto-generated.\n")
fmt.Fprintf(w, "// Command: %s\n\n", commandLine())
for _, ns := range strings.Split(*flagThriftNS, ",") {
fmt.Fprintf(w, "namespace %s\n", strings.TrimSpace(ns))
}
io.WriteString(w, "\n")
for _, structType := range list {
//structName := thriftPublicType(structType.Name)
structName := goPublicType(structType.Name)
fmt.Fprintf(w, "// %s was auto-generated.\n", structName)
if structType.Desc != "" {
if !strings.HasSuffix(structType.Desc, ".") {
structType.Desc += "."
}
fmt.Fprintf(w, "// %s\n", structType.Desc)
}
if structType.File != "" {
fmt.Fprintf(w, "// Source: %s\n", structType.File)
}
fmt.Fprintf(w, "struct %s {\n", structName)
fields := make(map[string]string)
for _, structField := range structType.Fields {
if structField.Type == "null" {
continue
}
var t string
if structField.IsStruct {
//t = thriftPublicType(structField.Type)
t = goPublicType(structField.Type)
} else {
t = thriftTypeConv.Get(structField.Type)
}
var line strings.Builder
if _, required := structType.Required[structField.Name]; required {
io.WriteString(&line, "required ")
} else {
io.WriteString(&line, "optional ")
}
if structField.IsSlice {
fmt.Fprintf(&line, "list<%s>", t)
} else {
io.WriteString(&line, t)
}
name := thriftPublicType(structField.Name)
if v, exists := thriftReservedWords[name]; exists {
name = v
}
fmt.Fprintf(&line, " %s;", name)
fields[name] = line.String()
}
keys := make([]string, 0, len(fields))
for key := range fields {
keys = append(keys, key)
}
sort.Strings(keys)
for i, key := range keys {
fmt.Fprintf(w, " %d: %s\n", i+1, fields[key])
}
fmt.Fprintf(w, "}\n\n")
}
return nil
}