main.go 6.0 KB

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