main.go 7.7 KB

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