From 621ce6ac7bf1857774d7cc47d127655463864796 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Tue, 23 Jan 2024 02:36:32 +0000 Subject: [PATCH] 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 Co-authored-by: yp05327 <576951401@qq.com> Co-committed-by: yp05327 <576951401@qq.com> --- checks/migrations.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/checks/migrations.go b/checks/migrations.go index d139f79..000b3fb 100644 --- a/checks/migrations.go +++ b/checks/migrations.go @@ -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 }