github.com/oNaiPs/go-generate-fast@v0.3.0/src/core/golist/golist.go (about) 1 package golist 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "os/exec" 8 "strings" 9 10 "go.uber.org/zap" 11 ) 12 13 type PackageError struct { 14 ImportStack []string // shortest path from package named on command line to this one 15 Pos string // position of error (if present, file:line:col) 16 Err string // the error itself 17 } 18 19 type Package struct { 20 Dir string // directory containing package sources 21 GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) 22 // Error information 23 Incomplete bool // this package or a dependency has an error 24 Error *PackageError // error loading package 25 } 26 27 type PkgError struct { 28 Error *string 29 Package string 30 } 31 32 // TODO see alternative 33 // https://github.com/uber-go/mock/blob/fcaca4af4e64b707bdb0773ec92441c524bce3d0/mockgen/mockgen.go#L836 34 35 func ModulesAndErrors(args []string) []PkgError { 36 if len(args) == 0 { 37 args = []string{"./..."} 38 } 39 40 cmd := exec.Command("go", append([]string{ 41 "list", "-e", "-json=GoFiles,Dir,Incomplete,Error,DepsErrors", 42 }, args...)...) 43 44 zap.S().Debug("Running command: ", strings.Join(cmd.Args, " ")) 45 46 // Get the output of the command 47 output, err := cmd.Output() 48 if err != nil { 49 zap.S().Error("Error executing command: ", err) 50 strError := err.Error() 51 return []PkgError{{Error: &strError}} 52 } 53 54 zap.S().Debug("go list output:\n", string(output)) 55 56 dec := json.NewDecoder(strings.NewReader(string(output))) 57 58 pkgErrors := []PkgError{} 59 60 for { 61 var pkg Package 62 63 err := dec.Decode(&pkg) 64 if err == io.EOF { 65 // all done 66 break 67 } 68 if err != nil { 69 zap.S().Error("Error parsing JSON: ", err) 70 strError := err.Error() 71 return []PkgError{{Error: &strError}} 72 } 73 74 if pkg.Error != nil { 75 strError := fmt.Sprintf("%s %s", pkg.Error.Pos, pkg.Error.Err) 76 pkgErrors = append(pkgErrors, PkgError{Error: &strError}) 77 continue 78 } 79 80 for _, file := range pkg.GoFiles { 81 fileLocation := fmt.Sprintf("%s/%s", pkg.Dir, file) 82 pkgErrors = append(pkgErrors, PkgError{Package: fileLocation}) 83 } 84 } 85 86 return pkgErrors 87 }