forked from tkrajina/typescriptify-golang-structs
/
main.go
175 lines (148 loc) · 3.85 KB
/
main.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
package main
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"strings"
"text/template"
"time"
)
type arrayImports []string
func (i *arrayImports) String() string {
return "// custom imports:\n\n" + strings.Join(*i, "\n")
}
func (i *arrayImports) Set(value string) error {
*i = append(*i, value)
return nil
}
const TEMPLATE = `package main
import (
"fmt"
"{{ .ModelsPackage }}"
"github.com/tkrajina/typescriptify-golang-structs/typescriptify"
)
func main() {
t := typescriptify.New()
t.CreateInterface = {{ .Interface }}
{{ range $key, $value := .InitParams }} t.{{ $key }}={{ $value }}
{{ end }}
{{ range .Structs }} t.Add({{ . }}{})
{{ end }}
{{ range .CustomImports }} t.AddImport("{{ . }}")
{{ end }}
err := t.ConvertToFile("{{ .TargetFile }}")
if err != nil {
panic(err.Error())
}
fmt.Println("OK")
}`
type Params struct {
ModelsPackage string
TargetFile string
Structs []string
InitParams map[string]interface{}
CustomImports arrayImports
Interface bool
}
func main() {
var p Params
var backupDir string
var customImports arrayImports
flag.StringVar(&p.ModelsPackage, "package", "", "Path of the package with models")
flag.StringVar(&p.TargetFile, "target", "", "Target typescript file")
flag.StringVar(&backupDir, "backup", "", "Directory where backup files are saved")
flag.BoolVar(&p.Interface, "interface", false, "Create interfaces (not classes)")
flag.Var(&customImports, "import", "Typescript import for your custom type, repeat this option for each import needed")
flag.Parse()
structs := []string{}
for _, structOrGoFile := range flag.Args() {
if strings.HasSuffix(structOrGoFile, ".go") {
fmt.Println("Parsing:", structOrGoFile)
fileStructs, err := GetGolangFileStructs(structOrGoFile)
if err != nil {
panic(fmt.Sprintf("Error loading/parsing golang file %s: %s", structOrGoFile, err.Error()))
}
structs = append(structs, fileStructs...)
} else {
structs = append(structs, structOrGoFile)
}
}
if len(p.ModelsPackage) == 0 {
fmt.Fprintln(os.Stderr, "No package given")
os.Exit(1)
}
if len(p.TargetFile) == 0 {
fmt.Fprintln(os.Stderr, "No target file")
os.Exit(1)
}
packageParts := strings.Split(p.ModelsPackage, "/")
pckg := packageParts[len(packageParts)-1]
t := template.Must(template.New("").Parse(TEMPLATE))
filename, err := ioutil.TempDir(os.TempDir(), "")
handleErr(err)
filename = fmt.Sprintf("%s/typescriptify_%d.go", filename, time.Now().Nanosecond())
f, err := os.Create(filename)
handleErr(err)
defer f.Close()
structsArr := make([]string, 0)
for _, str := range structs {
str = strings.TrimSpace(str)
if len(str) > 0 {
structsArr = append(structsArr, pckg+"."+str)
}
}
p.Structs = structsArr
p.InitParams = map[string]interface{}{
"BackupDir": fmt.Sprintf(`"%s"`, backupDir),
}
err = t.Execute(f, p)
handleErr(err)
cmd := exec.Command("go", "run", filename)
fmt.Println(strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(string(output))
handleErr(err)
}
fmt.Println(string(output))
}
func GetGolangFileStructs(filename string) ([]string, error) {
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, filename, nil, 0)
if err != nil {
return nil, err
}
v := &AVisitor{}
ast.Walk(v, f)
return v.structs, nil
}
type AVisitor struct {
structNameCandidate string
structs []string
}
func (v *AVisitor) Visit(node ast.Node) ast.Visitor {
if node != nil {
switch t := node.(type) {
case *ast.Ident:
v.structNameCandidate = t.Name
case *ast.StructType:
if len(v.structNameCandidate) > 0 {
v.structs = append(v.structs, v.structNameCandidate)
v.structNameCandidate = ""
}
default:
v.structNameCandidate = ""
}
}
return v
}
func handleErr(err error) {
if err != nil {
panic(err.Error())
}
}