github.com/daixiang0/gci@v0.13.0/pkg/section/local_module.go (about) 1 package section 2 3 import ( 4 "fmt" 5 "strings" 6 7 "golang.org/x/tools/go/packages" 8 9 "github.com/daixiang0/gci/pkg/parse" 10 "github.com/daixiang0/gci/pkg/specificity" 11 ) 12 13 const LocalModuleType = "localmodule" 14 15 type LocalModule struct { 16 Paths []string 17 } 18 19 func (m *LocalModule) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { 20 for _, modPath := range m.Paths { 21 // also check path etc. 22 if strings.HasPrefix(spec.Path, modPath) { 23 return specificity.LocalModule{} 24 } 25 } 26 27 return specificity.MisMatch{} 28 } 29 30 func (m *LocalModule) String() string { 31 return LocalModuleType 32 } 33 34 func (m *LocalModule) Type() string { 35 return LocalModuleType 36 } 37 38 // Configure configures the module section by finding the module 39 // for the current path 40 func (m *LocalModule) Configure() error { 41 modPaths, err := findLocalModules() 42 if err != nil { 43 return err 44 } 45 m.Paths = modPaths 46 return nil 47 } 48 49 func findLocalModules() ([]string, error) { 50 packages, err := packages.Load( 51 // find the package in the current dir and load its module 52 // NeedFiles so there is some more info in package errors 53 &packages.Config{Mode: packages.NeedModule | packages.NeedFiles}, 54 ".", 55 ) 56 if err != nil { 57 return nil, fmt.Errorf("failed to load local modules: %v", err) 58 } 59 60 uniqueModules := make(map[string]struct{}) 61 62 for _, pkg := range packages { 63 if len(pkg.Errors) != 0 { 64 return nil, fmt.Errorf("error reading local packages: %v", pkg.Errors) 65 } 66 if pkg.Module != nil { 67 uniqueModules[pkg.Module.Path] = struct{}{} 68 } 69 } 70 71 modPaths := make([]string, 0, len(uniqueModules)) 72 for mod := range uniqueModules { 73 modPaths = append(modPaths, mod) 74 } 75 76 return modPaths, nil 77 }