main.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package main
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "go/build"
  7. "io"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "regexp"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. )
  17. var directory = flag.String("pwd", "", "Working directory of Xray vprotogen.")
  18. // envFile returns the name of the Go environment configuration file.
  19. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166
  20. func envFile() (string, error) {
  21. if file := os.Getenv("GOENV"); file != "" {
  22. if file == "off" {
  23. return "", errors.New("GOENV=off")
  24. }
  25. return file, nil
  26. }
  27. dir, err := os.UserConfigDir()
  28. if err != nil {
  29. return "", err
  30. }
  31. if dir == "" {
  32. return "", errors.New("missing user-config dir")
  33. }
  34. return filepath.Join(dir, "go", "env"), nil
  35. }
  36. // GetRuntimeEnv returns the value of runtime environment variable,
  37. // that is set by running following command: `go env -w key=value`.
  38. func GetRuntimeEnv(key string) (string, error) {
  39. file, err := envFile()
  40. if err != nil {
  41. return "", err
  42. }
  43. if file == "" {
  44. return "", errors.New("missing runtime env file")
  45. }
  46. var data []byte
  47. var runtimeEnv string
  48. data, readErr := os.ReadFile(file)
  49. if readErr != nil {
  50. return "", readErr
  51. }
  52. envStrings := strings.Split(string(data), "\n")
  53. for _, envItem := range envStrings {
  54. envItem = strings.TrimSuffix(envItem, "\r")
  55. envKeyValue := strings.Split(envItem, "=")
  56. if strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {
  57. runtimeEnv = strings.TrimSpace(envKeyValue[1])
  58. }
  59. }
  60. return runtimeEnv, nil
  61. }
  62. // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.
  63. func GetGOBIN() string {
  64. // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command`
  65. GOBIN := os.Getenv("GOBIN")
  66. if GOBIN == "" {
  67. var err error
  68. // The one set by user by running `go env -w GOBIN=/path`
  69. GOBIN, err = GetRuntimeEnv("GOBIN")
  70. if err != nil {
  71. // The default one that Golang uses
  72. return filepath.Join(build.Default.GOPATH, "bin")
  73. }
  74. if GOBIN == "" {
  75. return filepath.Join(build.Default.GOPATH, "bin")
  76. }
  77. return GOBIN
  78. }
  79. return GOBIN
  80. }
  81. func whichProtoc(suffix, targetedVersion string) (string, error) {
  82. protoc := "protoc" + suffix
  83. path, err := exec.LookPath(protoc)
  84. if err != nil {
  85. return "", fmt.Errorf(`
  86. Command "%s" not found.
  87. Make sure that %s is in your system path or current path.
  88. Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases
  89. `, protoc, protoc, protoc, targetedVersion)
  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 "", errors.New("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 "", errors.New("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+)`)
  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. /*
  162. targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/XTLS/Xray-core/HEAD/core/config.pb.go")
  163. if err != nil {
  164. fmt.Println(err)
  165. os.Exit(1)
  166. }
  167. */
  168. targetedVersion := ""
  169. protoc, err := whichProtoc(suffix, targetedVersion)
  170. if err != nil {
  171. fmt.Println(err)
  172. os.Exit(1)
  173. }
  174. installedVersion, err := getInstalledProtocVersion(protoc)
  175. if err != nil {
  176. fmt.Println(err)
  177. os.Exit(1)
  178. }
  179. if needToUpdate(targetedVersion, installedVersion) {
  180. fmt.Printf(`
  181. You are using an old protobuf version, please update to v%s or later.
  182. Download it from https://github.com/protocolbuffers/protobuf/releases
  183. * Protobuf version used in xray project: v%s
  184. * Protobuf version you have installed: v%s
  185. `, targetedVersion, targetedVersion, installedVersion)
  186. os.Exit(1)
  187. }
  188. protoFilesMap := make(map[string][]string)
  189. walkErr := filepath.Walk(pwd, func(path string, info os.FileInfo, err error) error {
  190. if err != nil {
  191. fmt.Println(err)
  192. return err
  193. }
  194. if info.IsDir() {
  195. return nil
  196. }
  197. dir := filepath.Dir(path)
  198. filename := filepath.Base(path)
  199. if strings.HasSuffix(filename, ".proto") {
  200. path = path[len(pwd)+1:]
  201. protoFilesMap[dir] = append(protoFilesMap[dir], path)
  202. }
  203. return nil
  204. })
  205. if walkErr != nil {
  206. fmt.Println(walkErr)
  207. os.Exit(1)
  208. }
  209. for _, files := range protoFilesMap {
  210. for _, relProtoFile := range files {
  211. args := []string{
  212. "--go_out", pwd,
  213. "--go_opt", "paths=source_relative",
  214. "--go-grpc_out", pwd,
  215. "--go-grpc_opt", "paths=source_relative",
  216. "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix),
  217. "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix),
  218. }
  219. args = append(args, relProtoFile)
  220. cmd := exec.Command(protoc, args...)
  221. cmd.Env = append(cmd.Env, os.Environ()...)
  222. cmd.Dir = pwd
  223. output, cmdErr := cmd.CombinedOutput()
  224. if len(output) > 0 {
  225. fmt.Println(string(output))
  226. }
  227. if cmdErr != nil {
  228. fmt.Println(cmdErr)
  229. os.Exit(1)
  230. }
  231. }
  232. }
  233. }