feat(cmd): Support proto incremental generation to implement the code change

pull/2835/head
darrenzzy 2 years ago
parent 1d50f50262
commit 8b8f64a294
  1. 35
      cmd/kratos/internal/proto/server/server.go
  2. 4
      cmd/kratos/internal/proto/server/template.go

@ -79,19 +79,48 @@ func run(_ *cobra.Command, args []string) {
to := filepath.Join(targetDir, strings.ToLower(s.Service)+".go")
if _, err := os.Stat(to); !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "%s already exists: %s\n", s.Service, to)
continue
s.checkRepeatedMethod(to)
}
b, err := s.execute()
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile(to, b, 0o644); err != nil {
log.Fatal(err)
if s.ExistFile {
file, err := os.OpenFile(to, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
log.Fatal(err)
}
if _, err = file.Write(b); err != nil {
log.Fatal(err)
}
} else {
if err := os.WriteFile(to, b, 0o644); err != nil {
log.Fatal(err)
}
}
fmt.Println(to)
}
}
func (s *Service) checkRepeatedMethod(to string) {
contents, err := os.ReadFile(to)
if err != nil {
log.Fatal(err)
}
methods := make([]*Method, 0, len(s.Methods))
for _, method := range s.Methods {
if !(strings.Contains(string(contents), method.Request) &&
strings.Contains(string(contents), method.Reply) &&
strings.Contains(string(contents), method.Name)) {
methods = append(methods, method)
}
}
s.Methods = methods
s.ExistFile = true
}
func getMethodType(streamsRequest, streamsReturns bool) MethodType {
if !streamsRequest && !streamsReturns {
return unaryType

@ -8,6 +8,7 @@ import (
//nolint:lll
var serviceTemplate = `
{{- /* delete empty line */ -}}
{{- if eq .ExistFile false }}
package service
import (
@ -32,6 +33,8 @@ func New{{ .Service }}Service() *{{ .Service }}Service {
return &{{ .Service }}Service{}
}
{{- end }}
{{- $s1 := "google.protobuf.Empty" }}
{{ range .Methods }}
{{- if eq .Type 1 }}
@ -103,6 +106,7 @@ type Service struct {
UseIO bool
UseContext bool
ExistFile bool
}
// Method is a proto method.

Loading…
Cancel
Save