github.com/doytsujin/wwhrd@v0.2.1/walker.go (about) 1 package main 2 3 import ( 4 "go/parser" 5 "go/token" 6 "os" 7 "path/filepath" 8 "strings" 9 10 "github.com/ryanuber/go-license" 11 ) 12 13 func WalkImports(root string) (map[string]bool, error) { 14 15 pkgs := make(map[string]bool) 16 17 var walkFn = func(path string, info os.FileInfo, err error) error { 18 if info.IsDir() { 19 name := info.Name() 20 if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") || name == "testdata" { 21 return filepath.SkipDir 22 } 23 return nil 24 } 25 if filepath.Ext(path) != ".go" { 26 return nil 27 } 28 29 fs := token.NewFileSet() 30 f, err := parser.ParseFile(fs, path, nil, parser.ImportsOnly) 31 if err != nil { 32 return err 33 } 34 35 for _, s := range f.Imports { 36 p := strings.Replace(s.Path.Value, "\"", "", -1) 37 pkgs[p] = true 38 } 39 return nil 40 } 41 42 if err := filepath.Walk(root, walkFn); err != nil { 43 return nil, err 44 } 45 46 return pkgs, nil 47 } 48 49 func GetLicenses(root string, list map[string]bool) map[string]*license.License { 50 51 lics := make(map[string]*license.License) 52 53 for k := range list { 54 fpath := filepath.Join(root, "vendor", k) 55 pkg, err := os.Stat(fpath) 56 if err != nil { 57 continue 58 } 59 if pkg.IsDir() { 60 l, err := license.NewFromDir(fpath) 61 if err != nil { 62 // the package might be nested inside a larger package, we try to find 63 // the license starting from the beginning of the path. 64 pak := strings.Split(k, "/") 65 var path string 66 for x, y := range pak { 67 if x < 1 { 68 path = filepath.Join(root, "vendor", y) 69 } else { 70 path = filepath.Join(path, y) 71 } 72 if l, err := license.NewFromDir(path); err != nil { 73 continue 74 } else { 75 // We found a license in the leftmost package, that's enough for now 76 lics[k] = l 77 break 78 } 79 } 80 if lics[k] == nil { 81 // if our search didn't bear any fruit, ¯\_(ツ)_/¯ 82 lics[k] = &license.License{ 83 Type: "unrecognized", 84 Text: "unrecognized license", 85 File: "", 86 } 87 } 88 continue 89 } 90 lics[k] = l 91 } 92 } 93 94 return lics 95 }