-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfile.go
77 lines (71 loc) · 1.87 KB
/
file.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package fake
import (
"fmt"
"go/ast"
"go/token"
"io"
"slices"
"github.com/rs/zerolog/log"
"github.com/sonalys/fake/internal/imports"
)
type ParsedFile struct {
Generator *Generator
Size int
Ref *ast.File
PkgPath string
PkgName string
Imports map[string]*imports.ImportEntry
OriginalImports map[string]*imports.ImportEntry
ImportsPathMap map[string]*imports.ImportEntry
UsedImports map[string]struct{}
importResolved bool
importAlias string
}
func (f *ParsedFile) ListInterfaces(names ...string) []*ParsedInterface {
var resp []*ParsedInterface
// Iterate through the declarations in the file
for _, decl := range f.Ref.Decls {
decl, ok := decl.(*ast.GenDecl)
if !ok || decl.Tok != token.TYPE {
continue
}
for _, spec := range decl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok || len(names) > 0 && !slices.Contains(names, typeSpec.Name.Name) {
continue
}
interfaceType, ok := typeSpec.Type.(*ast.InterfaceType)
if !ok {
continue
}
cur := &ParsedInterface{
ParsedFile: f,
Type: typeSpec,
Ref: interfaceType,
Name: typeSpec.Name.Name,
}
cur.GenericsTypes, cur.GenericsNames = cur.getGenericsInfo()
resp = append(resp, cur)
}
}
return resp
}
func (f *ParsedFile) writeImports(w io.Writer) {
// Write import statements
fmt.Fprintf(w, "import (\n")
fmt.Fprintf(w, "\t\"fmt\"\n")
fmt.Fprintf(w, "\t\"testing\"\n")
fmt.Fprintf(w, "\tmockSetup \"github.com/sonalys/fake/boilerplate\"\n")
for name := range f.UsedImports {
info, ok := f.Imports[name]
if !ok {
log.Fatal().Msg("inconsistency between usedImports and imports state")
}
fmt.Fprintf(w, "\t")
if info.Alias != "" && info.Alias != info.PackageInfo.Name {
fmt.Fprintf(w, "%s ", info.Alias)
}
fmt.Fprintf(w, "\"%s\"\n", info.Path)
}
fmt.Fprintf(w, ")\n\n")
}