-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgenerate_values.py
executable file
·82 lines (76 loc) · 2.58 KB
/
generate_values.py
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
#!/usr/bin/env python
from gotypes import types, imports
local_imports = [
"strings"
]
res = "// Code generated by generate_values.py; DO NOT EDIT.\n"
res += "\n"
res += "package cli\n"
res += "\n"
res += "import (\n"
for pkg in sorted(imports + local_imports):
res += "\t\"%s\"\n" % pkg
res += ")\n"
for (typ, name, _, _) in types:
safe_typ = typ.replace(".", "")
res += "\n"
res += "// []%s\n" % typ
res += "\n"
res += "var (\n"
res += "\t_ Value = (*%sValues)(nil)\n" % safe_typ
res += "\t_ Getter = (*%sValues)(nil)\n" % safe_typ
res += "\t_ Emptier = (*%sValues)(nil)\n" % safe_typ
res += "\t_ Typer = (*%sValues)(nil)\n" % safe_typ
res += ")\n"
res += "\n"
res += "type %sValues []%s\n" % (safe_typ, typ)
res += "\n"
res += "func new%sValues(p *[]%s) *%sValues {\n" % (name, typ, safe_typ)
res += "\treturn (*%sValues)(p)\n" % safe_typ
res += "}\n"
res += "\n"
res += "func (vs *%sValues) Set(val string) error {\n" % safe_typ
res += "\trest := val\n"
res += "\tfor rest != \"\" {\n"
res += "\t\tidx := strings.IndexByte(rest, ',')\n"
res += "\t\tif idx != -1 {\n"
res += "\t\t\tval = rest[:idx]\n"
res += "\t\t\trest = rest[idx+1:]\n"
res += "\t\t} else {\n"
res += "\t\t\tval = rest\n"
res += "\t\t\trest = \"\"\n"
res += "\t\t}\n"
res += "\n"
res += "\t\tvar def %s\n" % typ
res += "\t\t*vs = append(*vs, def)\n"
res += "\t\tif err := (*%sValue)(&(*vs)[len(*vs)-1]).Set(val); err != nil {\n" % safe_typ
res += "\t\t\treturn err\n"
res += "\t\t}\n"
res += "\t}\n"
res += "\n"
res += "\treturn nil\n"
res += "}\n"
res += "\n"
res += "func (vs *%sValues) String() string {\n" % safe_typ
res += "\tif len(*vs) == 0 {\n"
res += "\t\treturn \"\"\n"
res += "\t}\n"
res += "\n"
res += "\tvar buf strings.Builder\n"
res += "\t_, _ = buf.WriteString((*%sValue)(&(*vs)[0]).String())\n" % safe_typ
res += "\n"
res += "\tfor i := 1; i < len(*vs); i++ {\n"
res += "\t\t_ = buf.WriteByte(',')\n"
res += "\t\t_, _ = buf.WriteString((*%sValue)(&(*vs)[i]).String())\n" % safe_typ
res += "\t}\n"
res += "\n"
res += "\treturn buf.String()\n"
res += "}\n"
res += "\n"
res += "func (v *%sValues) Empty() bool { return len(*v) == 0 }\n" % safe_typ
res += "\n"
res += "func (v *%sValues) Get() interface{} { return []%s(*v) }\n" % (safe_typ, typ)
res += "\n"
res += "func (*%sValues) Type() string { return \"[]%s\" }\n" % (safe_typ, typ)
with open("./values_gen.go", "w") as f:
f.write(res)