main.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  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. // 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 V2Ray 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. pwd, err := os.Getwd()
  139. if err != nil {
  140. fmt.Println("Can not get current working directory.")
  141. os.Exit(1)
  142. }
  143. GOBIN := GetGOBIN()
  144. binPath := os.Getenv("PATH")
  145. pathSlice := []string{pwd, GOBIN, binPath}
  146. binPath = strings.Join(pathSlice, string(os.PathListSeparator))
  147. os.Setenv("PATH", binPath)
  148. suffix := ""
  149. if runtime.GOOS == "windows" {
  150. suffix = ".exe"
  151. }
  152. targetedVersion, err := getProjectProtocVersion("https://raw.githubusercontent.com/v2fly/v2ray-core/HEAD/config.pb.go")
  153. if err != nil {
  154. fmt.Println(err)
  155. os.Exit(1)
  156. }
  157. protoc, err := whichProtoc(suffix, targetedVersion)
  158. if err != nil {
  159. fmt.Println(err)
  160. os.Exit(1)
  161. }
  162. if linkPath, err := os.Readlink(protoc); err == nil {
  163. protoc = linkPath
  164. }
  165. installedVersion, err := getInstalledProtocVersion(protoc)
  166. if err != nil {
  167. fmt.Println(err)
  168. os.Exit(1)
  169. }
  170. if needToUpdate(targetedVersion, installedVersion) {
  171. fmt.Printf(`
  172. You are using an old protobuf version, please update to v%s or later.
  173. Download it from https://github.com/protocolbuffers/protobuf/releases
  174. * Protobuf version used in V2Ray project: v%s
  175. * Protobuf version you have installed: v%s
  176. `, targetedVersion, targetedVersion, installedVersion)
  177. os.Exit(1)
  178. }
  179. protoFilesMap := make(map[string][]string)
  180. walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  181. if err != nil {
  182. fmt.Println(err)
  183. return err
  184. }
  185. if info.IsDir() {
  186. return nil
  187. }
  188. dir := filepath.Dir(path)
  189. filename := filepath.Base(path)
  190. if strings.HasSuffix(filename, ".proto") &&
  191. filename != "typed_message.proto" &&
  192. filename != "descriptor.proto" {
  193. protoFilesMap[dir] = append(protoFilesMap[dir], path)
  194. }
  195. return nil
  196. })
  197. if walkErr != nil {
  198. fmt.Println(walkErr)
  199. os.Exit(1)
  200. }
  201. for _, files := range protoFilesMap {
  202. for _, relProtoFile := range files {
  203. args := []string{
  204. "-I", fmt.Sprintf("%v/../include", filepath.Dir(protoc)),
  205. "-I", ".",
  206. "--go_out", pwd,
  207. "--go_opt", "paths=source_relative",
  208. "--go-grpc_out", pwd,
  209. "--go-grpc_opt", "paths=source_relative",
  210. "--plugin", "protoc-gen-go=" + filepath.Join(GOBIN, "protoc-gen-go"+suffix),
  211. "--plugin", "protoc-gen-go-grpc=" + filepath.Join(GOBIN, "protoc-gen-go-grpc"+suffix),
  212. }
  213. args = append(args, relProtoFile)
  214. cmd := exec.Command(protoc, args...)
  215. cmd.Env = append(cmd.Env, os.Environ()...)
  216. output, cmdErr := cmd.CombinedOutput()
  217. if len(output) > 0 {
  218. fmt.Println(string(output))
  219. }
  220. if cmdErr != nil {
  221. fmt.Println(cmdErr)
  222. os.Exit(1)
  223. }
  224. }
  225. }
  226. normalizeWalkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  227. if err != nil {
  228. fmt.Println(err)
  229. return err
  230. }
  231. if info.IsDir() {
  232. return nil
  233. }
  234. filename := filepath.Base(path)
  235. if strings.HasSuffix(filename, ".pb.go") &&
  236. path != "config.pb.go" {
  237. if err := NormalizeGeneratedProtoFile(path); err != nil {
  238. fmt.Println(err)
  239. os.Exit(1)
  240. }
  241. }
  242. return nil
  243. })
  244. if normalizeWalkErr != nil {
  245. fmt.Println(normalizeWalkErr)
  246. os.Exit(1)
  247. }
  248. }
  249. func NormalizeGeneratedProtoFile(path string) error {
  250. fd, err := os.OpenFile(path, os.O_RDWR, 0o644)
  251. if err != nil {
  252. return err
  253. }
  254. _, err = fd.Seek(0, os.SEEK_SET)
  255. if err != nil {
  256. return err
  257. }
  258. out := bytes.NewBuffer(nil)
  259. scanner := bufio.NewScanner(fd)
  260. valid := false
  261. for scanner.Scan() {
  262. if !valid && !strings.HasPrefix(scanner.Text(), "package ") {
  263. continue
  264. }
  265. valid = true
  266. out.Write(scanner.Bytes())
  267. out.Write([]byte("\n"))
  268. }
  269. _, err = fd.Seek(0, os.SEEK_SET)
  270. if err != nil {
  271. return err
  272. }
  273. err = fd.Truncate(0)
  274. if err != nil {
  275. return err
  276. }
  277. _, err = io.Copy(fd, bytes.NewReader(out.Bytes()))
  278. if err != nil {
  279. return err
  280. }
  281. return nil
  282. }