main.go 4.6 KB

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