main.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "v2ray.com/core/common"
  13. )
  14. var protocMap = map[string]string{
  15. "windows": filepath.Join(os.Getenv("GOPATH"), "src", "v2ray.com", "core", ".dev", "protoc", "windows", "protoc.exe"),
  16. "darwin": filepath.Join(os.Getenv("GOPATH"), "src", "v2ray.com", "core", ".dev", "protoc", "macos", "protoc"),
  17. "linux": filepath.Join(os.Getenv("GOPATH"), "src", "v2ray.com", "core", ".dev", "protoc", "linux", "protoc"),
  18. }
  19. var (
  20. repo = flag.String("repo", "", "Repo for protobuf generation, such as v2ray.com/core")
  21. )
  22. func main() {
  23. flag.Parse()
  24. protofiles := make(map[string][]string)
  25. protoc := protocMap[runtime.GOOS]
  26. gosrc := filepath.Join(os.Getenv("GOPATH"), "src")
  27. reporoot := filepath.Join(os.Getenv("GOPATH"), "src", *repo)
  28. filepath.Walk(reporoot, func(path string, info os.FileInfo, err error) error {
  29. if err != nil {
  30. fmt.Println(err)
  31. return err
  32. }
  33. if info.IsDir() {
  34. return nil
  35. }
  36. dir := filepath.Dir(path)
  37. filename := filepath.Base(path)
  38. if strings.HasSuffix(filename, ".proto") {
  39. protofiles[dir] = append(protofiles[dir], path)
  40. }
  41. return nil
  42. })
  43. for _, files := range protofiles {
  44. args := []string{"--proto_path", gosrc, "--go_out", "plugins=grpc:" + gosrc}
  45. args = append(args, files...)
  46. cmd := exec.Command(protoc, args...)
  47. cmd.Env = append(cmd.Env, os.Environ()...)
  48. output, err := cmd.CombinedOutput()
  49. if len(output) > 0 {
  50. fmt.Println(string(output))
  51. }
  52. if err != nil {
  53. fmt.Println(err)
  54. }
  55. }
  56. common.Must(filepath.Walk(reporoot, func(path string, info os.FileInfo, err error) error {
  57. if err != nil {
  58. fmt.Println(err)
  59. return err
  60. }
  61. if info.IsDir() {
  62. return nil
  63. }
  64. if !strings.HasSuffix(info.Name(), ".pb.go") {
  65. return nil
  66. }
  67. content, err := ioutil.ReadFile(path)
  68. if err != nil {
  69. return err
  70. }
  71. content = bytes.Replace(content, []byte("\"golang.org/x/net/context\""), []byte("\"context\""), 1)
  72. pos := bytes.Index(content, []byte("\npackage"))
  73. if pos > 0 {
  74. content = content[pos+1:]
  75. }
  76. return ioutil.WriteFile(path, content, info.Mode())
  77. }))
  78. }