protoc.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package generator
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "os/exec"
  7. "path"
  8. "strings"
  9. )
  10. func findVendorDir() string {
  11. pwd, err := os.Getwd()
  12. if err != nil {
  13. log.Printf("getwd error: %s", err)
  14. }
  15. for dir := pwd; dir != "/" && dir != "."; dir = path.Dir(dir) {
  16. vendorDir := path.Join(dir, "vendor")
  17. if s, err := os.Stat(vendorDir); err == nil && s.IsDir() {
  18. return vendorDir
  19. }
  20. }
  21. return ""
  22. }
  23. // Protoc run protoc generator go source code
  24. func Protoc(protoFile, protocExec, gen string, paths []string) error {
  25. if protocExec == "" {
  26. protocExec = "protoc"
  27. }
  28. if gen == "" {
  29. gen = "gogofast"
  30. }
  31. paths = append(paths, ".", os.Getenv("GOPATH"))
  32. vendorDir := findVendorDir()
  33. if vendorDir != "" {
  34. paths = append(paths, vendorDir)
  35. }
  36. args := []string{"--proto_path", strings.Join(paths, ":"), fmt.Sprintf("--%s_out=plugins=grpc:.", gen), path.Base(protoFile)}
  37. log.Printf("run protoc %s", strings.Join(args, " "))
  38. protoc := exec.Command(protocExec, args...)
  39. protoc.Stdout = os.Stdout
  40. protoc.Stderr = os.Stderr
  41. protoc.Dir = path.Dir(protoFile)
  42. return protoc.Run()
  43. }