main.go 7.5 KB

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