-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli_gen.py.tpl
217 lines (193 loc) · 8.21 KB
/
cli_gen.py.tpl
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
{{- /* Go Template */ -}}
# Code generated by {{.Generator}} {{.GeneratorVersion}}, DO NOT EDIT.
from dataclasses import dataclass
import typing
{{- /* Child commands */}}
{{range .Commands}}
@dataclass
class {{.CLIInputClassName}}:
{{range $Index, $Option := .Options -}}
{{$Option.InputFieldName}}: {{$Option.InputFieldType}} = {{$Option.DefaultLiteral}}{{"\n "}}
{{- end}}
{{range $Index, $Argument := .Arguments -}}
{{$Argument.InputFieldName}}: {{$Argument.InputFieldType}} = {{$Argument.InputFieldType}}(){{"\n "}}
{{- end}}
pass
class {{.CLIClassName}}:
{{range $Index, $Subcommand := .Subcommands -}}
{{$Subcommand.SubcommandFieldName}}: {{$Subcommand.SubcommandFieldType}} = {{$Subcommand.SubcommandFieldType}}(){{"\n "}}
{{- end}}
FUNC: typing.Callable[[None,list[str],{{.CLIInputClassName}},Exception],None] = None
def resolve_{{.CLIInputClassName}}(rest_args: list[str])->{{.CLIInputClassName}}:
input = {{.CLIInputClassName}}()
arguments = []
for i, arg in enumerate(rest_args):
if arg == "--":
arguments += rest_args[i+1:]
break
if not arg.startswith("-"):
arguments.append(arg)
continue
split = arg.split("=", 1)
opt_name, assign = split[0], len(split) > 1
{{range $Index, $Option := .Options}}
if opt_name == {{$Option.NameLiteral}}{{if $Option.ShortNameLiteral}} or opt_name == {{$Option.ShortNameLiteral}}{{end}}:
if not assign:
{{if eq $Option.InputFieldType "bool"}}split.append("True")
{{else}}raise Exception("value is not specified to option "+ opt_name)
{{end}}
input.{{$Option.InputFieldName}} = parse_value({{$Option.InputFieldType}}, split[1])
continue
{{end}}
raise Exception("unsupported option " + opt_name)
{{range $Index, $Argument := .Arguments -}}
{{- if $Argument.Variadic -}}
if len(arguments) <= {{$Index}} - 1:
raise Exception("too few arguments")
input.{{$Argument.InputFieldName}} = parse_value({{$Argument.InputFieldType}}, *arguments[{{$Index}}:])
{{- else -}}
if len(arguments) <= {{$Index}}:
raise Exception("too few arguments")
input.{{$Argument.InputFieldName}} = parse_value({{$Argument.InputFieldType}}, arguments[{{$Index}}])
{{- end -}}{{"\n "}}
{{- end}}
return input
{{end}}
{{- /* Root command */}}
{{with .Program}}
@dataclass
class {{.CLIInputClassName}}:
{{range $Index, $Option := .Options -}}
{{$Option.InputFieldName}}: {{$Option.InputFieldType}} = {{$Option.DefaultLiteral}}{{"\n "}}
{{- end}}
{{range $Index, $Argument := .Arguments -}}
{{$Argument.InputFieldName}}: {{$Argument.InputFieldType}} = {{$Argument.InputFieldType}}(){{"\n "}}
{{- end}}
pass
class {{.CLIClassName}}:
{{range $Index, $Subcommand := .Subcommands -}}
{{$Subcommand.SubcommandFieldName}}: {{$Subcommand.SubcommandFieldType}} = {{$Subcommand.SubcommandFieldType}}(){{"\n "}}
{{- end}}
FUNC: typing.Callable[[None,list[str],{{.CLIInputClassName}},Exception],None] = None
def resolve_{{.CLIInputClassName}}(rest_args: list[str])->{{.CLIInputClassName}}:
input = {{.CLIInputClassName}}()
arguments = []
for i, arg in enumerate(rest_args):
if arg == "--":
arguments += rest_args[i+1:]
break
if not arg.startswith("-"):
arguments.append(arg)
continue
split = arg.split("=", 1)
opt_name, assign = split[0], len(split) > 1
{{range $Index, $Option := .Options}}
if opt_name == {{$Option.NameLiteral}}{{if $Option.ShortNameLiteral}} or opt_name == {{$Option.ShortNameLiteral}}{{end}}:
if not assign:
{{if eq $Option.InputFieldType "bool"}}split.append("True")
{{else}}raise Exception("value is not specified to option "+ opt_name)
{{end}}
input.{{$Option.InputFieldName}} = parse_value({{$Option.InputFieldType}}, split[1])
continue
{{end}}
raise Exception("unsupported option " + opt_name)
{{range $Index, $Argument := .Arguments -}}
{{- if $Argument.Variadic -}}
if len(arguments) <= {{$Index}} - 1:
raise Exception("too few arguments")
input.{{$Argument.InputFieldName}} = parse_value({{$Argument.InputFieldType}}, *arguments[{{$Index}}:])
{{- else -}}
if len(arguments) <= {{$Index}}:
raise Exception("too few arguments")
input.{{$Argument.InputFieldName}} = parse_value({{$Argument.InputFieldType}}, arguments[{{$Index}}])
{{- end -}}{{"\n "}}
{{- end}}
return input
{{end}}
{{/* Entry point */ -}}
def run(cli: CLI, args: list[str]):
r = resolve_subcommand(args)
subcommand_path, rest_args = r.subcommand, r.rest_args
joined_subcommand = " ".join(subcommand_path)
{{with .Program}}
if joined_subcommand == {{.FullPathLiteral}}:
if not cli.{{.CLIFuncMethodChain}}:
raise Exception("unsupported subcommand \"" + {{.FullPathLiteral}} + "\": cli.{{.CLIFuncMethodChain}} not assigned")
ex: Exception = None
input: {{.CLIInputClassName}} = None
try:
input = resolve_{{.CLIInputClassName}}(rest_args)
except Exception as e:
ex = e
cli.{{.CLIFuncMethodChain}}(subcommand_path, input, ex)
{{end}}
{{range .Commands}}
if joined_subcommand == {{.FullPathLiteral}}:
if not cli.{{.CLIFuncMethodChain}}:
raise Exception("unsupported subcommand \"" + {{.FullPathLiteral}} + "\": cli.{{.CLIFuncMethodChain}} not assigned")
ex: Exception = None
input: {{.CLIInputClassName}} = None
try:
input = resolve_{{.CLIInputClassName}}(rest_args)
except Exception as e:
ex = e
cli.{{.CLIFuncMethodChain}}(subcommand_path, input, ex)
{{end}}
raise Exception("subcommand not found: " + joined_subcommand)
@dataclass
class ResolveSubcommandResult:
subcommand: list[str]
rest_args: list[str]
def resolve_subcommand(args: list[str])->ResolveSubcommandResult:
if not args:
raise Exception("command line arguments are too few")
subcommand_set = {
{{with .Program}}{{.FullPathLiteral}},{{end}}
{{range .Commands}}{{.FullPathLiteral}},{{end}}
}
subcommand_path = []
for arg in args[1:]:
if arg == "--":
break
if " ".join(subcommand_path + [arg]) not in subcommand_set:
break
subcommand_path.append(arg)
return ResolveSubcommandResult(subcommand_path, args[1+len(subcommand_path):])
def parse_value(typ, *str_values: str) -> typing.Union[str, bool, float, int, tuple[str, ...], tuple[bool, ...], tuple[float, ...], tuple[int, ...]]:
try:
if typ == str:
return str(str_values[0])
if typ == bool:
if str_values[0] in {"", "0", "f", "F", "FALSE", "false", "False"}:
return False
if str_values[0] in {"1", "t", "T", "TRUE", "true", "True"}:
return True
raise Exception("could not convert string to bool: '" + str_values[0] + "'")
if typ == float:
return float(str_values[0])
if typ == int:
return int(str_values[0], base=0)
if typ == tuple[str,...]:
return tuple([parse_value(str, s) for s in str_values])
if typ == tuple[bool,...]:
return tuple([parse_value(bool, s) for s in str_values])
if typ == tuple[float,...]:
return tuple([parse_value(float, s) for s in str_values])
if typ == tuple[int,...]:
return tuple([parse_value(int, s) for s in str_values])
raise Exception("unsupported type")
except Exception as e:
e.add_note('fail to parse string value as ' + typ.__name__)
raise
{{/* Documents */ -}}
def get_doc(subcommand: list[str]) -> str:
joined_subcommand = " ".join(subcommand)
{{with .Program}}
if joined_subcommand == {{.FullPathLiteral}}:
return {{.DocText}}
{{end}}
{{range .Commands}}
if joined_subcommand == {{.FullPathLiteral}}:
return {{.DocText}}
{{end}}
raise Exception("subcommand not found: " + joined_subcommand)