Debian Codegraph @

cmd/showimp/main.go

raw
1 // showimp is a utility for displaying the imports in a package.
2 package main
3
4 import (
5 "flag"
6 "fmt"
7 "go/parser"
8 "go/token"
9 "os"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strings"
14
15 "github.com/kisom/goutils/die"
16 "github.com/kisom/goutils/logging"
17 )
18
19 var (
20 gopath string
21 project string
22 debug bool
23 )
24
25 var (
26 stdLibRegexp = regexp.MustCompile(`^\w+(/\w+)*$`)
27 sourceRegexp = regexp.MustCompile(`^[^.].*\.go$`)
28 log = logging.NewConsole()
29 imports = map[string]bool{}
30 fset = &token.FileSet{}
31 )
32
33 func debugf(format string, args ...interface{}) {
34 if debug {
35 fmt.Printf(format, args...)
36 }
37 }
38
39 func debugln(args ...interface{}) {
40 if debug {
41 fmt.Println(args...)
42 }
43 }
44
45 func init() {
46 gopath = os.Getenv("GOPATH")
47 if gopath == "" {
48 fmt.Fprintf(os.Stderr, "GOPATH isn't set, can't proceed.")
49 os.Exit(1)
50 }
51 gopath += "/src/"
52
53 wd, err := os.Getwd()
54 if err != nil {
55 fmt.Fprintf(os.Stderr, "Unable to establish working directory: %v", err)
56 os.Exit(1)
57 }
58
59 if !strings.HasPrefix(wd, gopath) {
60 fmt.Fprintf(os.Stderr, "Can't determine my location in the GOPATH.\n")
61 fmt.Fprintf(os.Stderr, "Working directory is %s\n", wd)
62 fmt.Fprintf(os.Stderr, "Go source path is %s\n", gopath)
63 os.Exit(1)
64 }
65
66 project = wd[len(gopath):]
67 }
68
69 func walkFile(path string, info os.FileInfo, err error) error {
70 if !sourceRegexp.MatchString(path) {
71 return nil
72 }
73
74 debugln(path)
75
76 f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
77 if err != nil {
78 return err
79 }
80
81 for _, importSpec := range f.Imports {
82 importPath := strings.Trim(importSpec.Path.Value, `"`)
83 if stdLibRegexp.MatchString(importPath) {
84 debugln("standard lib:", importPath)
85 continue
86 } else if strings.HasPrefix(importPath, project) {
87 debugln("internal import:", importPath)
88 continue
89 } else if strings.HasPrefix(importPath, "golang.org/") {
90 debugln("extended lib:", importPath)
91 continue
92 }
93 debugln("import:", importPath)
94 imports[importPath] = true
95 }
96
97 return nil
98 }
99
100 func main() {
101 flag.BoolVar(&debug, "v", false, "log debugging information")
102 flag.Parse()
103
104 err := filepath.Walk(".", walkFile)
105 die.If(err)
106
107 fmt.Println("External imports:")
108 importList := make([]string, 0, len(imports))
109 for imp := range imports {
110 importList = append(importList, imp)
111 }
112 sort.Strings(importList)
113
114 for _, imp := range importList {
115 fmt.Println("\t", imp)
116 }
117 }