package main import ( "fmt" "google.golang.org/protobuf/compiler/protogen" "strings" ) func main() { u := &Kit{ imports: map[string]string{}, } protogen.Options{}.Run(u.Generate) } type Kit struct { imports map[string]string } func (u *Kit) addImports(imp string) { u.imports[imp] = imp } func (u *Kit) Generate(plugin *protogen.Plugin) error { if len(plugin.Files) < 1 { return nil } for _, f := range plugin.Files { if len(f.Services) == 0 { continue } fname := f.GeneratedFilenamePrefix + ".ts" t := plugin.NewGeneratedFile(fname, f.GoImportPath) for _, s := range f.Messages { t.P(`export interface `, s.Desc.Name(), ` {`) for _, vv := range s.Fields { common := strings.TrimSpace(vv.Comments.Leading.String()) if common != "" { t.P(` `, common) } typ := []string{} isRequired := ":" if vv.Desc.IsMap() { fields := vv.Desc.Message().Fields() typ = append(typ, fmt.Sprintf(`{ [key: %s]: %s }`, getType(fields.Get(0).Kind().String()), getType(fields.Get(1).Kind().String()))) } else if vv.Desc.Kind().String() == "message" { //t.P(vv.Desc.Message().Fields()) //t.P(vv.Desc.Message().Name()) //if vv.Desc.Message().Fields().Get(0).Name() == "value" { // isRequired = "?:" // //typ = append(typ, getType(vv.Desc.Message().Fields().Get(0).Kind().String())) //} else { fullName := fmt.Sprintf("%v", vv.Desc.Message().FullName()) if strings.HasPrefix(fullName, "google.protobuf") && strings.HasSuffix(fullName, "Value") { isRequired = "?:" } typ = append(typ, getType(fmt.Sprintf("%v", vv.Desc.Message().Name()))) //} } else { typ = append(typ, getType(vv.Desc.Kind().String())) } //vtype := fmt.Sprintf("%v", vv.Desc.Kind()) //if vtype == "bytes" { // typ = append(typ, "Uint8Array") //} else if vtype == "message" { // if vv.Desc.IsMap() { // typ = append(typ, fmt.Sprintf(`{ [key: %s]: %s }`, fields.Get(0).Kind().String(), fields.Get(1).Kind().String())) // } else { // // } // // //for _,v:=range vv.Desc.Message().Fields(){ // // // //} // //t.P() // //typ = append(typ, "Uint8Array") //} else { // typ = append(typ, vtype) //} if vv.Desc.IsList() { typ = append(typ, "[]") } //t.P(vv.Desc) t.P(` `, vv.Desc.JSONName(), isRequired, ` `, strings.Join(typ, "")) } t.P(`}`) t.P() } } return nil } func getType(key string) string { mps := map[string]string{ "int32": "number", "bytes": "Uint8Array", "Int32Value": "number", "StringValue": "string", "bool": "boolean", } if v, ok := mps[key]; ok { return v } return key }