main.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package main
  2. import (
  3. "fmt"
  4. "go/build"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. )
  11. // envFile returns the name of the Go environment configuration file.
  12. // Copy from https://github.com/golang/go/blob/c4f2a9788a7be04daf931ac54382fbe2cb754938/src/cmd/go/internal/cfg/cfg.go#L150-L166
  13. func envFile() (string, error) {
  14. if file := os.Getenv("GOENV"); file != "" {
  15. if file == "off" {
  16. return "", fmt.Errorf("GOENV=off")
  17. }
  18. return file, nil
  19. }
  20. dir, err := os.UserConfigDir()
  21. if err != nil {
  22. return "", err
  23. }
  24. if dir == "" {
  25. return "", fmt.Errorf("missing user-config dir")
  26. }
  27. return filepath.Join(dir, "go", "env"), nil
  28. }
  29. // GetRuntimeEnv returns the value of runtime environment variable,
  30. // that is set by running following command: `go env -w key=value`.
  31. func GetRuntimeEnv(key string) (string, error) {
  32. file, err := envFile()
  33. if err != nil {
  34. return "", err
  35. }
  36. if file == "" {
  37. return "", fmt.Errorf("missing runtime env file")
  38. }
  39. var data []byte
  40. var runtimeEnv string
  41. data, readErr := os.ReadFile(file)
  42. if readErr != nil {
  43. return "", readErr
  44. }
  45. envStrings := strings.Split(string(data), "\n")
  46. for _, envItem := range envStrings {
  47. envItem = strings.TrimSuffix(envItem, "\r")
  48. envKeyValue := strings.Split(envItem, "=")
  49. if len(envKeyValue) == 2 && strings.TrimSpace(envKeyValue[0]) == key {
  50. runtimeEnv = strings.TrimSpace(envKeyValue[1])
  51. }
  52. }
  53. return runtimeEnv, nil
  54. }
  55. // GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.
  56. func GetGOBIN() string {
  57. // The one set by user explicitly by `export GOBIN=/path` or `env GOBIN=/path command`
  58. GOBIN := os.Getenv("GOBIN")
  59. if GOBIN == "" {
  60. var err error
  61. // The one set by user by running `go env -w GOBIN=/path`
  62. GOBIN, err = GetRuntimeEnv("GOBIN")
  63. if err != nil {
  64. // The default one that Golang uses
  65. return filepath.Join(build.Default.GOPATH, "bin")
  66. }
  67. if GOBIN == "" {
  68. return filepath.Join(build.Default.GOPATH, "bin")
  69. }
  70. return GOBIN
  71. }
  72. return GOBIN
  73. }
  74. func Run(binary string, args []string) ([]byte, error) {
  75. cmd := exec.Command(binary, args...)
  76. cmd.Env = append(cmd.Env, os.Environ()...)
  77. output, cmdErr := cmd.CombinedOutput()
  78. if cmdErr != nil {
  79. return nil, cmdErr
  80. }
  81. return output, nil
  82. }
  83. func RunMany(binary string, args, files []string) {
  84. fmt.Println("Processing...")
  85. maxTasks := make(chan struct{}, runtime.NumCPU())
  86. for _, file := range files {
  87. maxTasks <- struct{}{}
  88. go func(file string) {
  89. output, err := Run(binary, append(args, file))
  90. if err != nil {
  91. fmt.Println(err)
  92. } else if len(output) > 0 {
  93. fmt.Println(string(output))
  94. }
  95. <-maxTasks
  96. }(file)
  97. }
  98. }
  99. func main() {
  100. pwd, err := os.Getwd()
  101. if err != nil {
  102. fmt.Println("Can not get current working directory.")
  103. os.Exit(1)
  104. }
  105. GOBIN := GetGOBIN()
  106. binPath := os.Getenv("PATH")
  107. pathSlice := []string{pwd, GOBIN, binPath}
  108. binPath = strings.Join(pathSlice, string(os.PathListSeparator))
  109. os.Setenv("PATH", binPath)
  110. suffix := ""
  111. if runtime.GOOS == "windows" {
  112. suffix = ".exe"
  113. }
  114. gofmt := "gofmt" + suffix
  115. goimports := "gci" + suffix
  116. if gofmtPath, err := exec.LookPath(gofmt); err != nil {
  117. fmt.Println("Can not find", gofmt, "in system path or current working directory.")
  118. os.Exit(1)
  119. } else {
  120. gofmt = gofmtPath
  121. }
  122. if goimportsPath, err := exec.LookPath(goimports); err != nil {
  123. fmt.Println("Can not find", goimports, "in system path or current working directory.")
  124. os.Exit(1)
  125. } else {
  126. goimports = goimportsPath
  127. }
  128. rawFilesSlice := make([]string, 0, 1000)
  129. walkErr := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
  130. if err != nil {
  131. fmt.Println(err)
  132. return err
  133. }
  134. if info.IsDir() {
  135. return nil
  136. }
  137. dir := filepath.Dir(path)
  138. filename := filepath.Base(path)
  139. if strings.HasSuffix(filename, ".go") &&
  140. !strings.HasSuffix(filename, ".pb.go") &&
  141. !strings.Contains(dir, filepath.Join("testing", "mocks")) &&
  142. !strings.Contains(path, filepath.Join("main", "distro", "all", "all.go")) {
  143. rawFilesSlice = append(rawFilesSlice, path)
  144. }
  145. return nil
  146. })
  147. if walkErr != nil {
  148. fmt.Println(walkErr)
  149. os.Exit(1)
  150. }
  151. gofmtArgs := []string{
  152. "-s", "-l", "-e", "-w",
  153. }
  154. goimportsArgs := []string{
  155. "write",
  156. "--NoInlineComments",
  157. "--NoPrefixComments",
  158. "--Section", "Standard",
  159. "--Section", "Default",
  160. "--Section", "pkgPrefix(github.com/v2fly/v2ray-core)",
  161. }
  162. RunMany(gofmt, gofmtArgs, rawFilesSlice)
  163. RunMany(goimports, goimportsArgs, rawFilesSlice)
  164. fmt.Println("Do NOT forget to commit file changes.")
  165. }