/
tool.go
252 lines (224 loc) · 6.19 KB
/
tool.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2016 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package svctool implements svcmux/svcdec tools command line parsing
package svctool
import (
"bytes"
"context"
"flag"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/token"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"go.chromium.org/luci/common/logging/gologger"
)
// Service contains the result of parsing the generated code for a pRPC service.
type Service struct {
TypeName string
Node *ast.InterfaceType
Methods []*Method
}
type Method struct {
Name string
Node *ast.Field
InputType string
OutputType string
}
type Import struct {
Name string
Path string
}
// Tool is a helper class for svcmux and svcdec.
type Tool struct {
// Name of the tool, e.g. "svcmux" or "svcdec".
Name string
// OutputFilenameSuffix is the suffix of generated file names,
// e.g. "mux" or "dec" for foo_mux.go or foo_dec.go.
OutputFilenameSuffix string
// Set by ParseArgs from command-line arguments.
// Types are type names from the Go package defined by Dir or FileNames.
Types []string
// Output is the base name for the output file.
Output string
// Dir is a Go package's directory.
Dir string
// FileNames is a list of source files from a single Go package.
FileNames []string
}
func (t *Tool) usage() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", t.Name)
fmt.Fprintf(os.Stderr, "\t%s [flags] -type T [directory]\n", t.Name)
fmt.Fprintf(os.Stderr, "\t%s [flags] -type T files... # Must be a single package\n", t.Name)
flag.PrintDefaults()
}
func (t *Tool) parseFlags(args []string) []string {
var flags = flag.NewFlagSet(t.Name, flag.ExitOnError)
typeFlag := flags.String("type", "", "comma-separated list of type names; must be set")
flags.StringVar(&t.Output, "output", "", "output file name; default <type>_string.go")
flags.Usage = t.usage
flags.Parse(args)
splitTypes := strings.Split(*typeFlag, ",")
t.Types = make([]string, 0, len(splitTypes))
for _, typ := range splitTypes {
typ = strings.TrimSpace(typ)
if typ != "" {
t.Types = append(t.Types, typ)
}
}
if len(t.Types) == 0 {
fmt.Fprintln(os.Stderr, "type is not specified")
flags.Usage()
os.Exit(2)
}
return flags.Args()
}
// ParseArgs parses command arguments. Exits if they are invalid.
func (t *Tool) ParseArgs(args []string) {
args = t.parseFlags(args)
switch len(args) {
case 0:
args = []string{"."}
fallthrough
case 1:
info, err := os.Stat(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if info.IsDir() {
t.Dir = args[0]
t.FileNames, err = goFilesIn(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
break
}
fallthrough
default:
t.Dir = filepath.Dir(args[0])
t.FileNames = args
}
}
// GeneratorArgs is passed to the function responsible for generating files.
type GeneratorArgs struct {
PackageName string
Services []*Service
ExtraImports []Import
Out io.Writer
}
type Generator func(c context.Context, a *GeneratorArgs) error
// importSorted converts a map name -> path to []Import sorted by name.
func importSorted(imports map[string]string) []Import {
names := make([]string, 0, len(imports))
for n := range imports {
names = append(names, n)
}
sort.Strings(names)
result := make([]Import, len(names))
for i, n := range names {
result[i] = Import{n, imports[n]}
}
return result
}
// Run parses Go files and generates a new file using f.
func (t *Tool) Run(c context.Context, f Generator) error {
// Validate arguments.
if len(t.FileNames) == 0 {
return fmt.Errorf("files not specified")
}
if len(t.Types) == 0 {
return fmt.Errorf("types not specified")
}
// Determine output file name.
outputName := t.Output
if outputName == "" {
if t.Dir == "" {
return fmt.Errorf("neither output not dir are specified")
}
baseName := fmt.Sprintf("%s_%s.go", t.Types[0], t.OutputFilenameSuffix)
outputName = filepath.Join(t.Dir, strings.ToLower(baseName))
}
// Parse Go files and resolve specified types.
p := &parser{
fileSet: token.NewFileSet(),
types: t.Types,
}
if err := p.parsePackage(t.FileNames); err != nil {
return fmt.Errorf("could not parse .go files: %s", err)
}
if err := p.resolveServices(c); err != nil {
return err
}
// Run the generator.
var buf bytes.Buffer
genArgs := &GeneratorArgs{
PackageName: p.files[0].Name.Name,
Services: p.services,
ExtraImports: importSorted(p.extraImports),
Out: &buf,
}
if err := f(c, genArgs); err != nil {
return err
}
// Format the output.
src, err := format.Source(buf.Bytes())
if err != nil {
println(buf.String())
return fmt.Errorf("gofmt: %s", err)
}
// Write to file.
return ioutil.WriteFile(outputName, src, 0644)
}
// Main does some setup (arg parsing, logging), calls t.Run, prints any errors
// and exits.
func (t *Tool) Main(args []string, f Generator) {
c := gologger.StdConfig.Use(context.Background())
t.ParseArgs(args)
if err := t.Run(c, f); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
os.Exit(0)
}
// goFilesIn lists .go files in dir.
func goFilesIn(dir string) ([]string, error) {
pkg, err := build.ImportDir(dir, 0)
if err != nil {
return nil, fmt.Errorf("cannot process directory %s: %s", dir, err)
}
var names []string
names = append(names, pkg.GoFiles...)
names = append(names, pkg.CgoFiles...)
names = prefixDirectory(dir, names)
return names, nil
}
// prefixDirectory places the directory name on the beginning of each name in the list.
func prefixDirectory(directory string, names []string) []string {
if directory == "." {
return names
}
ret := make([]string, len(names))
for i, name := range names {
ret[i] = filepath.Join(directory, name)
}
return ret
}