forked from jschaf/pggen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_set.go
48 lines (41 loc) · 1.08 KB
/
import_set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package golang
import (
"sort"
"github.com/eddiefisher/pggen/internal/codegen/golang/gotype"
)
// ImportSet contains a set of imports required by one Go file.
type ImportSet struct {
imports map[string]struct{}
}
func NewImportSet() *ImportSet {
return &ImportSet{imports: make(map[string]struct{}, 4)}
}
// AddPackage adds a fully qualified package path to the set, like
// "github.com/eddiefisher/pggen/foo".
func (s *ImportSet) AddPackage(p string) {
s.imports[p] = struct{}{}
}
// AddType adds all fully qualified package paths needed for type and any child
// types.
func (s *ImportSet) AddType(typ gotype.Type) {
s.AddPackage(typ.Import())
comp, ok := typ.(*gotype.CompositeType)
if !ok {
return
}
for _, childType := range comp.FieldTypes {
s.AddType(childType)
}
}
// SortedPackages returns a new slice containing the sorted packages, suitable
// for an import statement.
func (s *ImportSet) SortedPackages() []string {
imps := make([]string, 0, len(s.imports))
for pkg := range s.imports {
if pkg != "" {
imps = append(imps, pkg)
}
}
sort.Strings(imps)
return imps
}