github.com/code-visible/golang@v0.0.0-20240214000051-0f9c587b0b32/module/module.go (about) 1 package module 2 3 import ( 4 "fmt" 5 "go/token" 6 "os" 7 "path/filepath" 8 9 "github.com/code-visible/golang/sourcepkg" 10 "github.com/code-visible/golang/utils" 11 ) 12 13 type Module struct { 14 Name string `json:"name"` 15 Path string `json:"path"` 16 Pkgs []*sourcepkg.SourcePkg `json:"pkgs"` 17 Files []string `json:"files"` 18 19 fs *token.FileSet 20 pkgs map[string]*sourcepkg.SourcePkg 21 } 22 23 // initialize module 24 func NewModule(name string, path string) (*Module, error) { 25 // make sure the given path is a directory 26 err := utils.MustDir(path) 27 if err != nil { 28 return nil, err 29 } 30 // get absolute path of module 31 absPath, err := filepath.Abs(path) 32 if err != nil { 33 return nil, err 34 } 35 // enter module as work path 36 err = os.Chdir(absPath) 37 if err != nil { 38 return nil, err 39 } 40 41 // initialize module struct 42 m := &Module{ 43 Name: name, 44 Path: absPath, 45 Pkgs: nil, 46 Files: nil, 47 fs: token.NewFileSet(), 48 pkgs: make(map[string]*sourcepkg.SourcePkg), 49 } 50 51 return m, nil 52 } 53 54 func (m *Module) ScanFiles() { 55 dirs := utils.ListDirs(m.Path, true) 56 57 for _, d := range dirs { 58 pkg, err := sourcepkg.NewSourcePkg(m.Name, d, m.fs) 59 if err != nil { 60 fmt.Printf("meet error while parse package, skipped, error: %s\n", err) 61 continue 62 } 63 pkg.ParseFiles() 64 65 m.pkgs[pkg.Name] = pkg 66 m.Pkgs = append(m.Pkgs, pkg) 67 68 // m.Files = append(m.Files, pkg.Files...) 69 } 70 71 // list all exported files 72 m.fs.Iterate(func(f *token.File) bool { 73 m.Files = append(m.Files, f.Name()) 74 return true 75 }) 76 77 }