main.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "go/build"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "regexp"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. )
  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 "", fmt.Errorf("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 "", fmt.Errorf("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 "", fmt.Errorf("missing runtime env file")
  45. }
  46. var data []byte
  47. var runtimeEnv string
  48. data, readErr := ioutil.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. errStr := fmt.Sprintf(`
  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. return "", fmt.Errorf(errStr)
  91. }
  92. return path, nil
  93. }
  94. func getProjectProtocVersion(url string) (string, error) {
  95. resp, err := http.Get(url)
  96. if err != nil {
  97. return "", fmt.Errorf("can not get the version of protobuf used in V2Ray project")
  98. }
  99. defer resp.Body.Close()
  100. body, err := io.ReadAll(resp.Body)
  101. if err != nil {
  102. return "", fmt.Errorf("can not read from body")
  103. }
  104. versionRegexp := regexp.MustCompile(`\/\/\s*protoc\s*v(\d+\.\d+\.\d+)`)
  105. matched := versionRegexp.FindStringSubmatch(string(body))
  106. return matched[1], nil
  107. }
  108. func getInstalledProtocVersion(protocPath string) (string, error) {
  109. cmd := exec.Command(protocPath, "--version")
  110. cmd.Env = append(cmd.Env, os.Environ()...)
  111. output, cmdErr := cmd.CombinedOutput()
  112. if cmdErr != nil {
  113. return "", cmdErr
  114. }
  115. versionRegexp := regexp.MustCompile(`protoc\s*(\d+\.\d+\.\d+)`)
  116. matched := versionRegexp.FindStringSubmatch(string(output))
  117. return matched[1], nil
  118. }
  119. func parseVersion(s string, width int) int64 {
  120. strList := strings.Split(s, ".")
  121. format := fmt.Sprintf("%%s%%0%ds", width)
  122. v := ""
  123. for _, value := range strList {
  124. v = fmt.Sprintf(format, v, value)
  125. }
  126. var result int64
  127. var err error
  128. if result, err = strconv.ParseInt(v, 10, 64); err != nil {
  129. return 0
  130. }
  131. return result
  132. }
  133. func needToUpdate(targetedVersion, installedVersion string) bool {
  134. vt := parseVersion(targetedVersion, 4)
  135. vi := parseVersion(installedVersion, 4)
  136. return vt > vi
  137. }
  138. func main() {
  139. pwd, err := os.Getwd()
  140. if err != nil {
  141. fmt.Println("Can not get current working directory.")
  142. os.Exit(1)
  143. }
  144. GOBIN := GetGOBIN()
  145. binPath := os.Getenv("PATH")
  146. pathSlice := []string{pwd, GOBIN, binPath}
  147. binPath = strings.Join(pathSlice, string(os.PathListSeparator))
  148. os.Setenv("PATH", binPath)
  149. suffix := ""
  150. if runtime.GOOS == "windows" {
  151. suffix = ".exe"
  152. }
  153. targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/v2fly/v2ray-core/HEAD/config.pb.go")
  154. if err != nil {
  155. fmt.Println(err)
  156. os.Exit(1)
  157. }
  158. protoc, err := whichProtoc(suffix, targetedVersion)
  159. if err != nil {
  160. fmt.Println(err)
  161. os.Exit(1)
  162. }
  163. if linkPath, err := os.Readlink(protoc); err == nil {
  164. protoc = linkPath
  165. }
  166. installedVersion, err := getInstalledProtocVersion(protoc)
  167. if err != nil {
  168. fmt.Println(err)
  169. os.Exit(1)
  170. }
  171. if needToUpdate(targetedVersion, installedVersion) {
  172. fmt.Printf(`
  173. You are using an old protobuf version, please update to v%s or later.
  174. Download it from https://github.com/protocolbuffers/protobuf/releases
  175. * Protobuf version used in V2Ray project: v%s
  176. * Protobuf version you have installed: v%s
  177. `, targetedVersion, targetedVersion, installedVersion)
  178. os.Exit(1)
  179. }
  180. protoFilesMap := make(map[string][]string)
  181. walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  182. if err != nil {
  183. fmt.Println(err)
  184. return err
  185. }
  186. if info.IsDir() {
  187. return nil
  188. }
  189. dir := filepath.Dir(path)
  190. filename := filepath.Base(path)
  191. if strings.HasSuffix(filename, ".proto") &&
  192. filename != "typed_message.proto" &&
  193. filename != "descriptor.proto" {
  194. protoFilesMap[dir] = append(protoFilesMap[dir], path)
  195. }
  196. return nil
  197. })
  198. if walkErr != nil {
  199. fmt.Println(walkErr)
  200. os.Exit(1)
  201. }
  202. for _, files := range protoFilesMap {
  203. for _, relProtoFile := range files {
  204. args := []string{
  205. "-I", fmt.Sprintf("%v/../include", filepath.Dir(protoc)),
  206. "-I", ".",
  207. "--go_out", pwd,
  208. "--go_opt", "paths=source_relative",
  209. "--go-grpc_out", pwd,
  210. "--go-grpc_opt", "paths=source_relative",
  211. "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix),
  212. "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix),
  213. }
  214. args = append(args, relProtoFile)
  215. cmd := exec.Command(protoc, args...)
  216. cmd.Env = append(cmd.Env, os.Environ()...)
  217. output, cmdErr := cmd.CombinedOutput()
  218. if len(output) > 0 {
  219. fmt.Println(string(output))
  220. }
  221. if cmdErr != nil {
  222. fmt.Println(cmdErr)
  223. os.Exit(1)
  224. }
  225. }
  226. }
  227. normalizeWalkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  228. if err != nil {
  229. fmt.Println(err)
  230. return err
  231. }
  232. if info.IsDir() {
  233. return nil
  234. }
  235. filename := filepath.Base(path)
  236. if strings.HasSuffix(filename, ".pb.go") &&
  237. path != "config.pb.go" {
  238. if err := NormalizeGeneratedProtoFile(path); err != nil {
  239. fmt.Println(err)
  240. os.Exit(1)
  241. }
  242. }
  243. return nil
  244. })
  245. if normalizeWalkErr != nil {
  246. fmt.Println(normalizeWalkErr)
  247. os.Exit(1)
  248. }
  249. }
  250. func NormalizeGeneratedProtoFile(path string) error {
  251. fd, err := os.OpenFile(path, os.O_RDWR, 0o644)
  252. if err != nil {
  253. return err
  254. }
  255. _, err = fd.Seek(0, os.SEEK_SET)
  256. if err != nil {
  257. return err
  258. }
  259. out := bytes.NewBuffer(nil)
  260. scanner := bufio.NewScanner(fd)
  261. valid := false
  262. for scanner.Scan() {
  263. if !valid && !strings.HasPrefix(scanner.Text(), "package ") {
  264. continue
  265. }
  266. valid = true
  267. out.Write(scanner.Bytes())
  268. out.Write([]byte("\n"))
  269. }
  270. _, err = fd.Seek(0, os.SEEK_SET)
  271. if err != nil {
  272. return err
  273. }
  274. err = fd.Truncate(0)
  275. if err != nil {
  276. return err
  277. }
  278. _, err = io.Copy(fd, bytes.NewReader(out.Bytes()))
  279. if err != nil {
  280. return err
  281. }
  282. return nil
  283. }