trpc.group/trpc-go/trpc-cmdline@v1.0.9/plugin/validate.go (about) 1 // Tencent is pleased to support the open source community by making tRPC available. 2 // 3 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 4 // All rights reserved. 5 // 6 // If you have downloaded a copy of the tRPC source code from Tencent, 7 // please note that tRPC source code is licensed under the Apache 2.0 License, 8 // A copy of the Apache 2.0 License is included in this file. 9 10 package plugin 11 12 import ( 13 "os" 14 "path/filepath" 15 16 "trpc.group/trpc-go/trpc-cmdline/config" 17 "trpc.group/trpc-go/trpc-cmdline/descriptor" 18 "trpc.group/trpc-go/trpc-cmdline/params" 19 "trpc.group/trpc-go/trpc-cmdline/parser" 20 "trpc.group/trpc-go/trpc-cmdline/util/pb" 21 ) 22 23 // Validate is validate plugin. 24 type Validate struct { 25 } 26 27 // Name return plugin's name. 28 func (p *Validate) Name() string { 29 return "validate" 30 } 31 32 // Check only run when language is supported. 33 func (p *Validate) Check(fd *descriptor.FileDescriptor, opt *params.Option) bool { 34 if !opt.SecvEnabled { 35 return false 36 } 37 support, ok := config.SupportValidate[opt.Language] 38 if !ok || !support { 39 return false 40 } 41 42 // Check if validation feature is enabled in pb and generate go files. 43 return parser.CheckSECVEnabled(fd) 44 } 45 46 // Run runs protoc-gen-validate to generate validate.pb.go 47 // 48 // Only supports a few programming languages. See: https://trpc.group/devsec/protoc-gen-secv 49 func (p *Validate) Run(fd *descriptor.FileDescriptor, opt *params.Option) error { 50 51 var ( 52 pbOutDir string 53 err error 54 ) 55 56 outputdir := opt.OutputDir 57 58 if !opt.RPCOnly { 59 stubDir := filepath.Join(outputdir, "stub") 60 61 pbPackage, err := parser.GetPackage(fd, opt.Language) 62 if err != nil { 63 return err 64 } 65 pbOutDir = filepath.Join(stubDir, pbPackage) 66 os.MkdirAll(pbOutDir, os.ModePerm) 67 } 68 69 opts := []pb.Option{ 70 pb.WithPb2ImportPath(fd.Pb2ImportPath), 71 pb.WithPkg2ImportPath(fd.Pkg2ImportPath), 72 pb.WithSecvEnabled(true), 73 } 74 // Generate ${protofile}.pb.validate.go 75 if !opt.RPCOnly { 76 err = pb.Protoc(opt.Protodirs, opt.Protofile, opt.Language, pbOutDir, opts...) 77 } else { 78 err = pb.Protoc(opt.Protodirs, opt.Protofile, opt.Language, outputdir, opts...) 79 } 80 return err 81 }