Add migration count check (#27)

Add checks for no matching of migration functions count and the length of `migrations` defined in `migrations.go`

For example, for `v284 -> v285`
![image](/attachments/e43c465e-d41f-4755-950d-d3565690ea2a)
remove line 556:
![image](/attachments/a8598239-f123-415a-8090-3bdb781ce6ab)
run `make lint-go-vet`:
![image](/attachments/7a55b7be-6c19-41b5-995f-98d4aa5a7100)

Reviewed-on: https://gitea.com/gitea/gitea-vet/pulls/27
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: yp05327 <576951401@qq.com>
Co-committed-by: yp05327 <576951401@qq.com>
This commit is contained in:
yp05327 2024-01-23 02:36:32 +00:00 committed by Lunny Xiao
parent 54da2444a7
commit 621ce6ac7b
1 changed files with 30 additions and 0 deletions

View File

@ -4,7 +4,9 @@
package checks
import (
"bufio"
"errors"
"os"
"os/exec"
"strings"
@ -24,6 +26,8 @@ var (
migrationImpBlockList = []string{
"code.gitea.io/gitea/modules/structs",
}
migrationImpPrefix = "code.gitea.io/gitea/models/migrations/v"
migrationFile = "migrations.go"
)
func checkMigrations(pass *analysis.Pass) (interface{}, error) {
@ -56,13 +60,39 @@ func checkMigrations(pass *analysis.Pass) (interface{}, error) {
}
imps := strings.Split(string(impsOut), "\n")
migrationCount := 0
for _, imp := range imps {
if stringInSlice(imp, migrationImpBlockList) {
pass.Reportf(0, "code.gitea.io/gitea/models/migrations cannot import the following packages: %s", migrationImpBlockList)
return nil, nil
}
if strings.HasPrefix(imp, migrationImpPrefix) {
goFilesCmd := exec.Command("go", "list", "-f", `{{join .GoFiles "\n"}}`, imp)
goFilesOut, err := goFilesCmd.Output()
if err != nil {
return nil, err
}
// the last item is empty we need to ignore it
migrationCount += len(strings.Split(string(goFilesOut), "\n")) - 1
}
}
mf, err := os.Open(migrationFile)
if err != nil {
return nil, err
}
defer mf.Close()
l := bufio.NewScanner(mf)
for l.Scan() {
if strings.Contains(l.Text(), "NewMigration(\"") {
migrationCount--
}
}
if migrationCount != 0 {
pass.Reportf(0, "migration files count does not match migrations lengths in %s", migrationFile)
}
return nil, nil
}