github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/cmd/vpm/tidy.go (about) 1 /* 2 * Copyright (c) 2024-present unTill Pro, Ltd. 3 * @author Alisher Nurmanov 4 */ 5 6 package main 7 8 import ( 9 "errors" 10 "path/filepath" 11 "slices" 12 "strings" 13 14 "github.com/spf13/cobra" 15 "github.com/voedger/voedger/pkg/goutils/logger" 16 17 "github.com/voedger/voedger/pkg/appdef" 18 "github.com/voedger/voedger/pkg/compile" 19 ) 20 21 func newTidyCmd(params *vpmParams) *cobra.Command { 22 cmd := &cobra.Command{ 23 Use: "tidy", 24 Short: "add missing and remove unused modules", 25 RunE: func(cmd *cobra.Command, args []string) error { 26 // packages_gen.go should be created before compiling 27 dirName := filepath.Base(params.Dir) 28 if err := createPackagesGen(nil, params.Dir, dirName, true); err != nil { 29 return err 30 } 31 32 compileRes, err := compile.Compile(params.Dir) 33 if err != nil { 34 logger.Error(err) 35 logger.Error("failed to compile, will try to exec 'go mod tidy' anyway") 36 } 37 if compileRes == nil { 38 return errors.New("failed to compile, check schemas") 39 } 40 41 return tidy(compileRes.NotFoundDeps, compileRes.AppDef, compileRes.ModulePath, params.Dir) 42 }, 43 } 44 return cmd 45 46 } 47 48 func tidy(notFoundDeps []string, appDef appdef.IAppDef, packagePath string, dir string) error { 49 // get imports and not found dependencies and try to get them via 'go get' 50 imports := append(getImports(appDef, packagePath), notFoundDeps...) 51 if err := getDependencies(dir, imports); err != nil { 52 return err 53 } 54 if err := createPackagesGen(imports, dir, packagePath, true); err != nil { 55 return err 56 } 57 return execGoModTidy(dir) 58 } 59 60 func getImports(appDef appdef.IAppDef, packagePath string) (imports []string) { 61 if appDef == nil { 62 return imports 63 } 64 excludedPaths := []string{compile.DummyAppName, appdef.SysPackagePath, packagePath} 65 appDef.Packages(func(localName, fullPath string) { 66 if !slices.Contains(excludedPaths, fullPath) { 67 imports = append(imports, fullPath) 68 } 69 }) 70 return imports 71 } 72 73 func getDependencies(dir string, imports []string) error { 74 for _, imp := range imports { 75 if strings.Contains(imp, "/") { 76 if err := execGoGet(dir, imp); err != nil { 77 return err 78 } 79 } 80 } 81 return nil 82 }