summaryrefslogtreecommitdiffstats
path: root/build/code-batch-process.go
blob: cc2ab680268c98b0e34acc1390fd9424c29dfc81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

//go:build ignore

package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	"code.gitea.io/gitea/build/codeformat"
)

// Windows has a limitation for command line arguments, the size can not exceed 32KB.
// So we have to feed the files to some tools (like gofmt) batch by batch

// We also introduce a `gitea-fmt` command, it does better import formatting than gofmt/goimports. `gitea-fmt` calls `gofmt` internally.

var optionLogVerbose bool

func logVerbose(msg string, args ...any) {
	if optionLogVerbose {
		log.Printf(msg, args...)
	}
}

func passThroughCmd(cmd string, args []string) error {
	foundCmd, err := exec.LookPath(cmd)
	if err != nil {
		log.Fatalf("can not find cmd: %s", cmd)
	}
	c := exec.Cmd{
		Path:   foundCmd,
		Args:   append([]string{cmd}, args...),
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	return c.Run()
}

type fileCollector struct {
	dirs            []string
	includePatterns []*regexp.Regexp
	excludePatterns []*regexp.Regexp
	batchSize       int
}

func newFileCollector(fileFilter string, batchSize int) (*fileCollector, error) {
	co := &fileCollector{batchSize: batchSize}
	if fileFilter == "go-own" {
		co.dirs = []string{
			"build",
			"cmd",
			"contrib",
			"tests",
			"models",
			"modules",
			"routers",
			"services",
		}
		co.includePatterns = append(co.includePatterns, regexp.MustCompile(`.*\.go$`))

		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`.*\bbindata\.go$`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`\.pb\.go$`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/gitea-repositories-meta`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/integration/migration-test`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`modules/git/tests`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`models/fixtures`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`models/migrations/fixtures`))
		co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`services/gitdiff/testdata`))
	}

	if co.dirs == nil {
		return nil, fmt.Errorf("unknown file-filter: %s", fileFilter)
	}
	return co, nil
}

func (fc *fileCollector) matchPatterns(path string, regexps []*regexp.Regexp) bool {
	path = strings.ReplaceAll(path, "\\", "/")
	for _, re := range regexps {
		if re.MatchString(path) {
			return true
		}
	}
	return false
}

func (fc *fileCollector) collectFiles() (res [][]string, err error) {
	var batch []string
	for _, dir := range fc.dirs {
		err = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
			include := len(fc.includePatterns) == 0 || fc.matchPatterns(path, fc.includePatterns)
			exclude := fc.matchPatterns(path, fc.excludePatterns)
			process := include && !exclude
			if !process {
				if d.IsDir() {
					if exclude {
						logVerbose("exclude dir %s", path)
						return filepath.SkipDir
					}
					// for a directory, if it is not excluded explicitly, we should walk into
					return nil
				}
				// for a file, we skip it if it shouldn't be processed
				logVerbose("skip process %s", path)
				return nil
			}
			if d.IsDir() {
				// skip dir, we don't add dirs to the file list now
				return nil
			}
			if len(batch) >= fc.batchSize {
				res = append(res, batch)
				batch = nil
			}
			batch = append(batch, path)
			return nil
		})
		if err != nil {
			return nil, err
		}
	}
	res = append(res, batch)
	return res, nil
}

// substArgFiles expands the {file-list} to a real file list for commands
func substArgFiles(args, files []string) []string {
	for i, s := range args {
		if s == "{file-list}" {
			newArgs := append(args[:i], files...)
			newArgs = append(newArgs, args[i+1:]...)
			return newArgs
		}
	}
	return args
}

func exitWithCmdErrors(subCmd string, subArgs []string, cmdErrors []error) {
	for _, err := range cmdErrors {
		if err != nil {
			if exitError, ok := err.(*exec.ExitError); ok {
				exitCode := exitError.ExitCode()
				log.Printf("run command failed (code=%d): %s %v", exitCode, subCmd, subArgs)
				os.Exit(exitCode)
			} else {
				log.Fatalf("run command failed (err=%s) %s %v", err, subCmd, subArgs)
			}
		}
	}
}

func parseArgs() (mainOptions map[string]string, subCmd string, subArgs []string) {
	mainOptions = map[string]string{}
	for i := 1; i < len(os.Args); i++ {
		arg := os.Args[i]
		if arg == "" {
			break
		}
		if arg[0] == '-' {
			arg = strings.TrimPrefix(arg, "-")
			arg = strings.TrimPrefix(arg, "-")
			fields := strings.SplitN(arg, "=", 2)
			if len(fields) == 1 {
				mainOptions[fields[0]] = "1"
			} else {
				mainOptions[fields[0]] = fields[1]
			}
		} else {
			subCmd = arg
			subArgs = os.Args[i+1:]
			break
		}
	}
	return
}

func showUsage() {
	fmt.Printf(`Usage: %[1]s [options] {command} [arguments]

Options:
  --verbose
  --file-filter=go-own
  --batch-size=100

Commands:
  %[1]s gofmt ...

Arguments:
  {file-list}     the file list

Example:
  %[1]s gofmt -s -d {file-list}

`, "file-batch-exec")
}

func newFileCollectorFromMainOptions(mainOptions map[string]string) (fc *fileCollector, err error) {
	fileFilter := mainOptions["file-filter"]
	if fileFilter == "" {
		fileFilter = "go-own"
	}
	batchSize, _ := strconv.Atoi(mainOptions["batch-size"])
	if batchSize == 0 {
		batchSize = 100
	}

	return newFileCollector(fileFilter, batchSize)
}

func containsString(a []string, s string) bool {
	for _, v := range a {
		if v == s {
			return true
		}
	}
	return false
}

func giteaFormatGoImports(files []string, doWriteFile bool) error {
	for _, file := range files {
		if err := codeformat.FormatGoImports(file, doWriteFile); err != nil {
			log.Printf("failed to format go imports: %s, err=%v", file, err)
			return err
		}
	}
	return nil
}

func main() {
	mainOptions, subCmd, subArgs := parseArgs()
	if subCmd == "" {
		showUsage()
		os.Exit(1)
	}
	optionLogVerbose = mainOptions["verbose"] != ""

	fc, err := newFileCollectorFromMainOptions(mainOptions)
	if err != nil {
		log.Fatalf("can not create file collector: %s", err.Error())
	}

	fileBatches, err := fc.collectFiles()
	if err != nil {
		log.Fatalf("can not collect files: %s", err.Error())
	}

	processed := 0
	var cmdErrors []error
	for _, files := range fileBatches {
		if len(files) == 0 {
			break
		}
		substArgs := substArgFiles(subArgs, files)
		logVerbose("batch cmd: %s %v", subCmd, substArgs)
		switch subCmd {
		case "gitea-fmt":
			if containsString(subArgs, "-d") {
				log.Print("the -d option is not supported by gitea-fmt")
			}
			cmdErrors = append(cmdErrors, giteaFormatGoImports(files, containsString(subArgs, "-w")))
			cmdErrors = append(cmdErrors, passThroughCmd("gofmt", append([]string{"-w", "-r", "interface{} -> any"}, substArgs...)))
			cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("GOFUMPT_PACKAGE"), "-extra"}, substArgs...)))
		default:
			log.Fatalf("unknown cmd: %s %v", subCmd, subArgs)
		}
		processed += len(files)
	}

	logVerbose("processed %d files", processed)
	exitWithCmdErrors(subCmd, subArgs, cmdErrors)
}