validate.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package module
  2. import (
  3. "github.com/envoyproxy/protoc-gen-validate/templates"
  4. "github.com/envoyproxy/protoc-gen-validate/templates/java"
  5. pgs "github.com/lyft/protoc-gen-star"
  6. pgsgo "github.com/lyft/protoc-gen-star/lang/go"
  7. "strings"
  8. )
  9. const (
  10. validatorName = "validator"
  11. langParam = "lang"
  12. moduleParam = "module"
  13. )
  14. type Module struct {
  15. *pgs.ModuleBase
  16. ctx pgsgo.Context
  17. }
  18. func Validator() pgs.Module { return &Module{ModuleBase: &pgs.ModuleBase{}} }
  19. func (m *Module) InitContext(ctx pgs.BuildContext) {
  20. m.ModuleBase.InitContext(ctx)
  21. m.ctx = pgsgo.InitContext(ctx.Parameters())
  22. }
  23. func (m *Module) Name() string { return validatorName }
  24. func (m *Module) Execute(targets map[string]pgs.File, pkgs map[string]pgs.Package) []pgs.Artifact {
  25. lang := m.Parameters().Str(langParam)
  26. m.Assert(lang != "", "`lang` parameter must be set")
  27. module := m.Parameters().Str(moduleParam)
  28. // Process file-level templates
  29. tpls := templates.Template(m.Parameters())[lang]
  30. m.Assert(tpls != nil, "could not find templates for `lang`: ", lang)
  31. for _, f := range targets {
  32. m.Push(f.Name().String())
  33. for _, msg := range f.AllMessages() {
  34. m.CheckRules(msg)
  35. }
  36. for _, tpl := range tpls {
  37. out := templates.FilePathFor(tpl)(f, m.ctx, tpl)
  38. // A nil path means no output should be generated for this file - as controlled by
  39. // implementation-specific FilePathFor implementations.
  40. // Ex: Don't generate Java validators for files that don't reference PGV.
  41. if out != nil {
  42. outPath := strings.TrimLeft(strings.ReplaceAll(out.String(), module, ""), "/")
  43. if opts := f.Descriptor().GetOptions(); opts != nil && opts.GetJavaMultipleFiles() && lang == "java" {
  44. // TODO: Only Java supports multiple file generation. If more languages add multiple file generation
  45. // support, the implementation should be made more inderect.
  46. for _, msg := range f.Messages() {
  47. m.AddGeneratorTemplateFile(java.JavaMultiFilePath(f, msg).String(), tpl, msg)
  48. }
  49. } else {
  50. m.AddGeneratorTemplateFile(outPath, tpl, f)
  51. }
  52. }
  53. }
  54. m.Pop()
  55. }
  56. return m.Artifacts()
  57. }
  58. var _ pgs.Module = (*Module)(nil)