You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

code-batch-process.go 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //go:build ignore
  4. package main
  5. import (
  6. "fmt"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "code.gitea.io/gitea/build/codeformat"
  15. )
  16. // Windows has a limitation for command line arguments, the size can not exceed 32KB.
  17. // So we have to feed the files to some tools (like gofmt) batch by batch
  18. // We also introduce a `gitea-fmt` command, it does better import formatting than gofmt/goimports. `gitea-fmt` calls `gofmt` internally.
  19. var optionLogVerbose bool
  20. func logVerbose(msg string, args ...interface{}) {
  21. if optionLogVerbose {
  22. log.Printf(msg, args...)
  23. }
  24. }
  25. func passThroughCmd(cmd string, args []string) error {
  26. foundCmd, err := exec.LookPath(cmd)
  27. if err != nil {
  28. log.Fatalf("can not find cmd: %s", cmd)
  29. }
  30. c := exec.Cmd{
  31. Path: foundCmd,
  32. Args: append([]string{cmd}, args...),
  33. Stdin: os.Stdin,
  34. Stdout: os.Stdout,
  35. Stderr: os.Stderr,
  36. }
  37. return c.Run()
  38. }
  39. type fileCollector struct {
  40. dirs []string
  41. includePatterns []*regexp.Regexp
  42. excludePatterns []*regexp.Regexp
  43. batchSize int
  44. }
  45. func newFileCollector(fileFilter string, batchSize int) (*fileCollector, error) {
  46. co := &fileCollector{batchSize: batchSize}
  47. if fileFilter == "go-own" {
  48. co.dirs = []string{
  49. "build",
  50. "cmd",
  51. "contrib",
  52. "tests",
  53. "models",
  54. "modules",
  55. "routers",
  56. "services",
  57. "tools",
  58. }
  59. co.includePatterns = append(co.includePatterns, regexp.MustCompile(`.*\.go$`))
  60. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`.*\bbindata\.go$`))
  61. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/gitea-repositories-meta`))
  62. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/integration/migration-test`))
  63. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`modules/git/tests`))
  64. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`models/fixtures`))
  65. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`models/migrations/fixtures`))
  66. co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`services/gitdiff/testdata`))
  67. }
  68. if co.dirs == nil {
  69. return nil, fmt.Errorf("unknown file-filter: %s", fileFilter)
  70. }
  71. return co, nil
  72. }
  73. func (fc *fileCollector) matchPatterns(path string, regexps []*regexp.Regexp) bool {
  74. path = strings.ReplaceAll(path, "\\", "/")
  75. for _, re := range regexps {
  76. if re.MatchString(path) {
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. func (fc *fileCollector) collectFiles() (res [][]string, err error) {
  83. var batch []string
  84. for _, dir := range fc.dirs {
  85. err = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
  86. include := len(fc.includePatterns) == 0 || fc.matchPatterns(path, fc.includePatterns)
  87. exclude := fc.matchPatterns(path, fc.excludePatterns)
  88. process := include && !exclude
  89. if !process {
  90. if d.IsDir() {
  91. if exclude {
  92. logVerbose("exclude dir %s", path)
  93. return filepath.SkipDir
  94. }
  95. // for a directory, if it is not excluded explicitly, we should walk into
  96. return nil
  97. }
  98. // for a file, we skip it if it shouldn't be processed
  99. logVerbose("skip process %s", path)
  100. return nil
  101. }
  102. if d.IsDir() {
  103. // skip dir, we don't add dirs to the file list now
  104. return nil
  105. }
  106. if len(batch) >= fc.batchSize {
  107. res = append(res, batch)
  108. batch = nil
  109. }
  110. batch = append(batch, path)
  111. return nil
  112. })
  113. if err != nil {
  114. return nil, err
  115. }
  116. }
  117. res = append(res, batch)
  118. return res, nil
  119. }
  120. // substArgFiles expands the {file-list} to a real file list for commands
  121. func substArgFiles(args, files []string) []string {
  122. for i, s := range args {
  123. if s == "{file-list}" {
  124. newArgs := append(args[:i], files...)
  125. newArgs = append(newArgs, args[i+1:]...)
  126. return newArgs
  127. }
  128. }
  129. return args
  130. }
  131. func exitWithCmdErrors(subCmd string, subArgs []string, cmdErrors []error) {
  132. for _, err := range cmdErrors {
  133. if err != nil {
  134. if exitError, ok := err.(*exec.ExitError); ok {
  135. exitCode := exitError.ExitCode()
  136. log.Printf("run command failed (code=%d): %s %v", exitCode, subCmd, subArgs)
  137. os.Exit(exitCode)
  138. } else {
  139. log.Fatalf("run command failed (err=%s) %s %v", err, subCmd, subArgs)
  140. }
  141. }
  142. }
  143. }
  144. func parseArgs() (mainOptions map[string]string, subCmd string, subArgs []string) {
  145. mainOptions = map[string]string{}
  146. for i := 1; i < len(os.Args); i++ {
  147. arg := os.Args[i]
  148. if arg == "" {
  149. break
  150. }
  151. if arg[0] == '-' {
  152. arg = strings.TrimPrefix(arg, "-")
  153. arg = strings.TrimPrefix(arg, "-")
  154. fields := strings.SplitN(arg, "=", 2)
  155. if len(fields) == 1 {
  156. mainOptions[fields[0]] = "1"
  157. } else {
  158. mainOptions[fields[0]] = fields[1]
  159. }
  160. } else {
  161. subCmd = arg
  162. subArgs = os.Args[i+1:]
  163. break
  164. }
  165. }
  166. return
  167. }
  168. func showUsage() {
  169. fmt.Printf(`Usage: %[1]s [options] {command} [arguments]
  170. Options:
  171. --verbose
  172. --file-filter=go-own
  173. --batch-size=100
  174. Commands:
  175. %[1]s gofmt ...
  176. Arguments:
  177. {file-list} the file list
  178. Example:
  179. %[1]s gofmt -s -d {file-list}
  180. `, "file-batch-exec")
  181. }
  182. func getGoVersion() string {
  183. goModFile, err := os.ReadFile("go.mod")
  184. if err != nil {
  185. log.Fatalf(`Faild to read "go.mod": %v`, err)
  186. os.Exit(1)
  187. }
  188. goModVersionRegex := regexp.MustCompile(`go \d+\.\d+`)
  189. goModVersionLine := goModVersionRegex.Find(goModFile)
  190. return string(goModVersionLine[3:])
  191. }
  192. func newFileCollectorFromMainOptions(mainOptions map[string]string) (fc *fileCollector, err error) {
  193. fileFilter := mainOptions["file-filter"]
  194. if fileFilter == "" {
  195. fileFilter = "go-own"
  196. }
  197. batchSize, _ := strconv.Atoi(mainOptions["batch-size"])
  198. if batchSize == 0 {
  199. batchSize = 100
  200. }
  201. return newFileCollector(fileFilter, batchSize)
  202. }
  203. func containsString(a []string, s string) bool {
  204. for _, v := range a {
  205. if v == s {
  206. return true
  207. }
  208. }
  209. return false
  210. }
  211. func giteaFormatGoImports(files []string, doWriteFile bool) error {
  212. for _, file := range files {
  213. if err := codeformat.FormatGoImports(file, doWriteFile); err != nil {
  214. log.Printf("failed to format go imports: %s, err=%v", file, err)
  215. return err
  216. }
  217. }
  218. return nil
  219. }
  220. func main() {
  221. mainOptions, subCmd, subArgs := parseArgs()
  222. if subCmd == "" {
  223. showUsage()
  224. os.Exit(1)
  225. }
  226. optionLogVerbose = mainOptions["verbose"] != ""
  227. fc, err := newFileCollectorFromMainOptions(mainOptions)
  228. if err != nil {
  229. log.Fatalf("can not create file collector: %s", err.Error())
  230. }
  231. fileBatches, err := fc.collectFiles()
  232. if err != nil {
  233. log.Fatalf("can not collect files: %s", err.Error())
  234. }
  235. processed := 0
  236. var cmdErrors []error
  237. for _, files := range fileBatches {
  238. if len(files) == 0 {
  239. break
  240. }
  241. substArgs := substArgFiles(subArgs, files)
  242. logVerbose("batch cmd: %s %v", subCmd, substArgs)
  243. switch subCmd {
  244. case "gitea-fmt":
  245. if containsString(subArgs, "-d") {
  246. log.Print("the -d option is not supported by gitea-fmt")
  247. }
  248. cmdErrors = append(cmdErrors, giteaFormatGoImports(files, containsString(subArgs, "-w")))
  249. cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("GOFUMPT_PACKAGE"), "-extra", "-lang", getGoVersion()}, substArgs...)))
  250. default:
  251. log.Fatalf("unknown cmd: %s %v", subCmd, subArgs)
  252. }
  253. processed += len(files)
  254. }
  255. logVerbose("processed %d files", processed)
  256. exitWithCmdErrors(subCmd, subArgs, cmdErrors)
  257. }