/
file.go
55 lines (51 loc) · 1.07 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
package helper
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"google.golang.org/protobuf/compiler/protogen"
"io"
"os"
"strings"
)
func Exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
func ParseGoFile(filepath string) ([]byte, map[string]struct{}) {
file, err := os.Open(filepath)
if err != nil {
return nil, nil
}
gosrc, err := io.ReadAll(file)
if err != nil {
return nil, nil
}
fnMap := make(map[string]struct{})
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", gosrc, 0)
if err != nil {
return gosrc, nil
}
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
fnMap[fn.Name.String()] = struct{}{}
}
}
return gosrc, fnMap
}
func GetFileBaseDir(file *protogen.File, config GenerateConfig) string {
if config.ModPath != "" {
return config.ModPath
}
projName := string(file.GoPackageName)
importDomain := strings.Split(string(file.GoImportPath), "/")[0]
return fmt.Sprintf("%s/projects/%s", importDomain, projName)
}