-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
69 lines (58 loc) · 1.52 KB
/
utils.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
package proto
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/jhump/protoreflect/desc/protoparse"
"google.golang.org/protobuf/reflect/protoreflect"
)
func parseProtoFiles(importPaths []string) (fds []protoreflect.FileDescriptor, err error) {
userDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("get user home dir: %w", err)
}
var ip []string
for _, importPath := range importPaths {
if importPath == "~" {
importPath = userDir
} else if strings.HasPrefix(importPath, "~/") {
importPath = filepath.Join(userDir, importPath[2:])
}
importPath, err = filepath.Abs(importPath)
if err != nil {
return nil, fmt.Errorf("getting absolute path for %q: %w", importPath, err)
}
if !strings.HasSuffix(importPath, "/") {
importPath += "/"
}
ip = append(ip, importPath)
}
parser := protoparse.Parser{
ImportPaths: ip,
}
var protoFiles []string
for _, importPath := range ip {
err := filepath.Walk(importPath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, ".proto") && !info.IsDir() {
protoFiles = append(protoFiles, strings.TrimPrefix(path, importPath))
}
return nil
})
if err != nil {
return nil, fmt.Errorf("walking import path %q: %w", importPath, err)
}
}
parsed, err := parser.ParseFiles(protoFiles...)
if err != nil {
return nil, fmt.Errorf("parsing proto files: %w", err)
}
for _, fd := range parsed {
fds = append(fds, fd.UnwrapFile())
}
return
}