forked from izumin5210/grapi
/
config.go
72 lines (62 loc) 路 2.05 KB
/
config.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
package protoc
import (
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
// Config stores setting params related protoc.
type Config struct {
ImportDirs []string `mapstructure:"import_dirs"`
ProtosDir string `mapstructure:"protos_dir"`
OutDir string `mapstructure:"out_dir"`
Plugins []*Plugin
}
// ProtoFiles returns .proto file paths.
func (c *Config) ProtoFiles(fs afero.Fs, rootDir string) ([]string, error) {
paths := []string{}
protosDir := filepath.Join(rootDir, c.ProtosDir)
err := afero.Walk(fs, protosDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return errors.WithStack(err)
}
if !info.IsDir() && filepath.Ext(path) == ".proto" {
paths = append(paths, path)
}
return nil
})
return paths, errors.WithStack(err)
}
// OutDirOf returns a directory path of protoc result output path for given proto file.
func (c *Config) OutDirOf(rootDir string, protoPath string) (string, error) {
protosDir := filepath.Join(rootDir, c.ProtosDir)
relProtoDir, err := filepath.Rel(protosDir, filepath.Dir(protoPath))
if strings.Contains(relProtoDir, "..") {
return "", errors.Errorf(".proto files should be included in %s", c.ProtosDir)
}
if err != nil {
return "", errors.Wrapf(err, ".proto files should be included in %s", c.ProtosDir)
}
return filepath.Join(c.OutDir, relProtoDir), nil
}
// Commands returns protoc command and arguments for given proto file.
func (c *Config) Commands(rootDir, protoPath string) ([][]string, error) {
cmds := make([][]string, 0, len(c.Plugins))
relProtoPath, _ := filepath.Rel(rootDir, protoPath)
outDir, err := c.OutDirOf(rootDir, protoPath)
if err != nil {
return nil, errors.WithStack(err)
}
for _, p := range c.Plugins {
args := []string{}
args = append(args, "-I", filepath.Dir(relProtoPath))
for _, dir := range c.ImportDirs {
args = append(args, "-I", dir)
}
args = append(args, p.toProtocArg(outDir))
args = append(args, relProtoPath)
cmds = append(cmds, append([]string{"protoc"}, args...))
}
return cmds, nil
}