forked from cloudwego/thriftgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
args.go
227 lines (193 loc) · 5.76 KB
/
args.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
// Copyright 2021 CloudWeGo 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 main
import (
"flag"
"fmt"
"log"
"os"
"strings"
"github.com/cloudwego/thriftgo/generator"
"github.com/cloudwego/thriftgo/generator/backend"
"github.com/cloudwego/thriftgo/plugin"
)
// StringSlice implements the flag.Value interface on string slices
// to allow a flag to be set multiple times.
type StringSlice []string
func (ss *StringSlice) String() string {
return fmt.Sprintf("%v", *ss)
}
// Set implements the flag.Value interface.
func (ss *StringSlice) Set(value string) error {
*ss = append(*ss, value)
return nil
}
// Arguments contains command line arguments for thriftgo.
type Arguments struct {
AskVersion bool
Recursive bool
Verbose bool
Quiet bool
CheckKeyword bool
OutputPath string
Includes StringSlice
Plugins StringSlice
Langs StringSlice
IDL string
}
// Output returns an output path for generated codes for the target language.
func (a *Arguments) Output(lang string) string {
if len(a.OutputPath) > 0 {
return a.OutputPath
}
return "./gen-" + lang
}
// UsedPlugins returns a list of plugin.Desc for plugins.
func (a *Arguments) UsedPlugins() (descs []*plugin.Desc, err error) {
for _, str := range a.Plugins {
desc, err := plugin.ParseCompactArguments(str)
if err != nil {
return nil, err
}
descs = append(descs, desc)
}
return
}
// Targets returns a list of generator.LangSpec for target languages.
func (a *Arguments) Targets() (specs []*generator.LangSpec, err error) {
for _, lang := range a.Langs {
desc, err := plugin.ParseCompactArguments(lang)
if err != nil {
return nil, err
}
spec := &generator.LangSpec{
Language: desc.Name,
Options: desc.Options,
}
specs = append(specs, spec)
}
return
}
// MakeLogFunc creates logging functions according to command line flags.
func (a *Arguments) MakeLogFunc() backend.LogFunc {
logs := backend.DummyLogFunc()
if !a.Quiet {
if a.Verbose {
logger := log.New(os.Stderr, "[INFO] ", 0)
logs.Info = func(v ...interface{}) {
logger.Println(v...)
}
}
logger := log.New(os.Stderr, "[WARN] ", 0)
logs.Warn = func(v ...interface{}) {
logger.Println(v...)
}
logs.MultiWarn = func(ws []string) {
for _, w := range ws {
logger.Println(w)
}
}
}
return logs
}
// BuildFlags initializes command line flags.
func (a *Arguments) BuildFlags() *flag.FlagSet {
f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
f.BoolVar(&a.AskVersion, "version", false, "")
f.BoolVar(&a.Recursive, "r", false, "")
f.BoolVar(&a.Recursive, "recurse", false, "")
f.BoolVar(&a.Verbose, "v", false, "")
f.BoolVar(&a.Verbose, "verbose", false, "")
f.BoolVar(&a.Quiet, "q", false, "")
f.BoolVar(&a.Quiet, "quiet", false, "")
f.StringVar(&a.OutputPath, "o", "", "")
f.StringVar(&a.OutputPath, "out", "", "")
f.Var(&a.Includes, "i", "")
f.Var(&a.Includes, "include", "")
f.Var(&a.Langs, "g", "")
f.Var(&a.Langs, "gen", "")
f.Var(&a.Plugins, "p", "")
f.Var(&a.Plugins, "plugin", "")
f.BoolVar(&a.CheckKeyword, "check-keywords", true, "")
f.Usage = help
return f
}
// Parse parse command line arguments.
func (a *Arguments) Parse(argv []string) error {
f := a.BuildFlags()
if err := f.Parse(argv[1:]); err != nil {
return err
}
if a.AskVersion {
return nil
}
rest := f.Args()
if len(rest) != 1 {
return fmt.Errorf("require exactly 1 argument for the IDL parameter, got: %d", len(rest))
}
a.IDL = rest[0]
return nil
}
func help() {
println("Version:", Version)
println(`Usage: thriftgo [options] file
Options:
--version Print the compiler version and exit.
-h, --help Print help message and exit.
-i, --include dir Add a search path for includes.
-o, --out dir Set the output location for generated files. (default: ./gen-*)
-r, --recurse Generate codes for includes recursively.
-v, --verbose Output detail logs.
-q, --quiet Suppress all warnings and informatic logs.
-g, --gen STR Specify the target language.
STR has the form language[:key1=val1[,key2[,key3=val3]]].
Keys and values are options passed to the backend.
Many options will not require values. Boolean options accept
"false", "true" and "" (empty is treated as "true").
-p, --plugin STR Specify an external plugin to invoke.
STR has the form plugin[=path][:key1=val1[,key2[,key3=val3]]].
--check-keywords Check if any identifer using a keyword in common languages.
Available generators (and options):
`)
// print backend options
for _, b := range g.AllBackend() {
name, lang := b.Name(), b.Lang()
println(fmt.Sprintf(" %s (%s):", name, lang))
println(align(b.Options()))
}
println()
os.Exit(2)
}
// align the help strings for plugin options.
func align(opts []plugin.Option) string {
var names, descs, ss []string
max := 0
for _, opt := range opts {
names = append(names, opt.Name)
descs = append(descs, opt.Desc)
if max <= len(opt.Name) {
max = len(opt.Name)
}
}
for i := range names {
rest := 2 + max - len(names[i])
ss = append(ss, fmt.Sprintf(
" %s:%s%s",
names[i],
strings.Repeat(" ", rest),
descs[i],
))
}
return strings.Join(ss, "\n")
}