main.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package main
  2. import (
  3. "fmt"
  4. "go/build"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. )
  16. // envFile returns the name of the Go environment configuration file.
  17. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166
  18. func envFile() (string, error) {
  19. if file := os.Getenv("GOENV"); file != "" {
  20. if file == "off" {
  21. return "", fmt.Errorf("GOENV=off")
  22. }
  23. return file, nil
  24. }
  25. dir, err := os.UserConfigDir()
  26. if err != nil {
  27. return "", err
  28. }
  29. if dir == "" {
  30. return "", fmt.Errorf("missing user-config dir")
  31. }
  32. return filepath.Join(dir, "go", "env"), nil
  33. }
  34. // GetRuntimeEnv returns the value of runtime environment variable,
  35. // that is set by running following command: `go env -w key=value`.
  36. func GetRuntimeEnv(key string) (string, error) {
  37. file, err := envFile()
  38. if err != nil {
  39. return "", err
  40. }
  41. if file == "" {
  42. return "", fmt.Errorf("missing runtime env file")
  43. }
  44. var data []byte
  45. var runtimeEnv string
  46. data, readErr := ioutil.ReadFile(file)
  47. if readErr != nil {
  48. return "", readErr
  49. }
  50. envStrings := strings.Split(string(data), "\n")
  51. for _, envItem := range envStrings {
  52. envItem = strings.TrimSuffix(envItem, "\r")
  53. envKeyValue := strings.Split(envItem, "=")
  54. if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {
  55. runtimeEnv = strings.TrimSpace(envKeyValue[1])
  56. }
  57. }
  58. return runtimeEnv, nil
  59. }
  60. // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.
  61. func GetGOBIN() string {
  62. // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command`
  63. GOBIN := os.Getenv("GOBIN")
  64. if GOBIN == "" {
  65. var err error
  66. // The one set by user by running `go env -w GOBIN=/path`
  67. GOBIN, err = GetRuntimeEnv("GOBIN")
  68. if err != nil {
  69. // The default one that Golang uses
  70. return filepath.Join(build.Default.GOPATH, "bin")
  71. }
  72. if GOBIN == "" {
  73. return filepath.Join(build.Default.GOPATH, "bin")
  74. }
  75. return GOBIN
  76. }
  77. return GOBIN
  78. }
  79. func whichProtoc(suffix, targetedVersion string) (string, error) {
  80. protoc := "protoc" + suffix
  81. path, err := exec.LookPath(protoc)
  82. if err != nil {
  83. errStr := fmt.Sprintf(`
  84. Command "%s" not found.
  85. Make sure that %s is in your system path or current path.
  86. Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases
  87. `, protoc, protoc, protoc, targetedVersion)
  88. return "", fmt.Errorf(errStr)
  89. }
  90. return path, nil
  91. }
  92. func getProjectProtocVersion(url string) (string, error) {
  93. resp, err := http.Get(url)
  94. if err != nil {
  95. return "", fmt.Errorf("can not get the version of protobuf used in V2Ray project")
  96. }
  97. defer resp.Body.Close()
  98. body, err := io.ReadAll(resp.Body)
  99. if err != nil {
  100. return "", fmt.Errorf("can not read from body")
  101. }
  102. versionRegexp := regexp.MustCompile(`\/\/\s*protoc\s*v(\d+\.\d+\.\d+)`)
  103. matched := versionRegexp.FindStringSubmatch(string(body))
  104. return matched[1], nil
  105. }
  106. func getInstalledProtocVersion(protocPath string) (string, error) {
  107. cmd := exec.Command(protocPath, "--version")
  108. cmd.Env = append(cmd.Env, os.Environ()...)
  109. output, cmdErr := cmd.CombinedOutput()
  110. if cmdErr != nil {
  111. return "", cmdErr
  112. }
  113. versionRegexp := regexp.MustCompile(`protoc\s*(\d+\.\d+\.\d+)`)
  114. matched := versionRegexp.FindStringSubmatch(string(output))
  115. return matched[1], nil
  116. }
  117. func parseVersion(s string, width int) int64 {
  118. strList := strings.Split(s, ".")
  119. format := fmt.Sprintf("%%s%%0%ds", width)
  120. v := ""
  121. for _, value := range strList {
  122. v = fmt.Sprintf(format, v, value)
  123. }
  124. var result int64
  125. var err error
  126. if result, err = strconv.ParseInt(v, 10, 64); err != nil {
  127. return 0
  128. }
  129. return result
  130. }
  131. func needToUpdate(targetedVersion, installedVersion string) bool {
  132. vt := parseVersion(targetedVersion, 4)
  133. vi := parseVersion(installedVersion, 4)
  134. return vt > vi
  135. }
  136. func main() {
  137. pwd, err := os.Getwd()
  138. if err != nil {
  139. fmt.Println("Can not get current working directory.")
  140. os.Exit(1)
  141. }
  142. GOBIN := GetGOBIN()
  143. binPath := os.Getenv("PATH")
  144. pathSlice := []string{pwd, GOBIN, binPath}
  145. binPath = strings.Join(pathSlice, string(os.PathListSeparator))
  146. os.Setenv("PATH", binPath)
  147. suffix := ""
  148. if runtime.GOOS == "windows" {
  149. suffix = ".exe"
  150. }
  151. targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/v2fly/v2ray-core/HEAD/config.pb.go")
  152. if err != nil {
  153. fmt.Println(err)
  154. os.Exit(1)
  155. }
  156. protoc, err := whichProtoc(suffix, targetedVersion)
  157. if err != nil {
  158. fmt.Println(err)
  159. os.Exit(1)
  160. }
  161. if linkPath, err := os.Readlink(protoc); err == nil {
  162. protoc = linkPath
  163. }
  164. installedVersion, err := getInstalledProtocVersion(protoc)
  165. if err != nil {
  166. fmt.Println(err)
  167. os.Exit(1)
  168. }
  169. if needToUpdate(targetedVersion, installedVersion) {
  170. fmt.Printf(`
  171. You are using an old protobuf version, please update to v%s or later.
  172. Download it from https://github.com/protocolbuffers/protobuf/releases
  173. * Protobuf version used in V2Ray project: v%s
  174. * Protobuf version you have installed: v%s
  175. `, targetedVersion, targetedVersion, installedVersion)
  176. os.Exit(1)
  177. }
  178. protoFilesMap := make(map[string][]string)
  179. walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  180. if err != nil {
  181. fmt.Println(err)
  182. return err
  183. }
  184. if info.IsDir() {
  185. return nil
  186. }
  187. dir := filepath.Dir(path)
  188. filename := filepath.Base(path)
  189. if strings.HasSuffix(filename, ".proto") &&
  190. filename != "typed_message.proto" &&
  191. filename != "descriptor.proto" {
  192. protoFilesMap[dir] = append(protoFilesMap[dir], path)
  193. }
  194. return nil
  195. })
  196. if walkErr != nil {
  197. fmt.Println(walkErr)
  198. os.Exit(1)
  199. }
  200. for _, files := range protoFilesMap {
  201. for _, relProtoFile := range files {
  202. args := []string{
  203. "-I", fmt.Sprintf("%v/../include", filepath.Dir(protoc)),
  204. "-I", fmt.Sprintf("."),
  205. "--go_out", pwd,
  206. "--go_opt", "paths=source_relative",
  207. "--go-grpc_out", pwd,
  208. "--go-grpc_opt", "paths=source_relative",
  209. "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix),
  210. "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix),
  211. }
  212. args = append(args, relProtoFile)
  213. cmd := exec.Command(protoc, args...)
  214. cmd.Env = append(cmd.Env, os.Environ()...)
  215. output, cmdErr := cmd.CombinedOutput()
  216. if len(output) > 0 {
  217. fmt.Println(string(output))
  218. }
  219. if cmdErr != nil {
  220. fmt.Println(cmdErr)
  221. os.Exit(1)
  222. }
  223. }
  224. }
  225. }