main.go 6.4 KB

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