/
file.go
101 lines (84 loc) · 2 KB
/
file.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
package xj2go
import (
"errors"
"log"
"os"
"os/exec"
"path"
"regexp"
"sort"
)
func checkFile(filename, pkg string) (string, error) {
if ok, err := pathExists(pkg); !ok {
os.Mkdir(pkg, 0755)
if err != nil {
return "", err
}
}
filename = path.Base(filename)
if filename[:1] == "." {
return "", errors.New("File could not start with '.'")
}
filename = pkg + "/" + filename + ".go"
if ok, _ := pathExists(filename); ok {
if err := os.Remove(filename); err != nil {
log.Fatal(err)
return "", err
}
}
return filename, nil
}
func writeStruct(filename, pkg string, strcts []strctMap) error {
re := regexp.MustCompile("\\[|\\]")
filename = re.ReplaceAllString(filename, "")
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer file.Close()
if err != nil {
log.Fatal(err)
return err
}
pkgLines := make(map[string]string)
strctLines := []string{}
var roots []string
strctsMap := make(map[string]strctMap)
for _, strct := range strcts {
for root := range strct {
roots = append(roots, root)
strctsMap[root] = strct
}
}
sort.Strings(roots)
for _, root := range roots {
strct := strctsMap[root]
for r, sns := range strct {
sort.Sort(byName(sns))
strctLines = append(strctLines, "type "+toProperCase(r)+" struct {\n")
for i := 0; i < len(sns); i++ {
if sns[i].Type == "time.Time" {
pkgLines["time.Time"] = "import \"time\"\n"
}
strctLines = append(strctLines, "\t"+toProperCase(sns[i].Name)+"\t"+sns[i].Type+"\t"+sns[i].Tag+"\n")
}
strctLines = append(strctLines, "}\n")
}
}
strctLines = append(strctLines, "\n")
file.WriteString("package " + pkg + "\n\n")
for _, pl := range pkgLines {
file.WriteString(pl)
}
for _, sl := range strctLines {
file.WriteString(sl)
}
ft := exec.Command("go", "fmt", filename)
if err := ft.Run(); err != nil {
log.Fatal(err)
return err
}
vt := exec.Command("go", "vet", filename)
if err := vt.Run(); err != nil {
log.Fatal(err)
return err
}
return nil
}