-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema_utils.go
192 lines (154 loc) · 4.68 KB
/
schema_utils.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
/*
Copyright 2019 Konstantin Vasilev (burmuley@gmail.com)
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.
*/
// Set of functions for processing schema data
package main
import (
"bytes"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"sync"
"text/template"
)
// bufWriter: reads from two channels `bCh` (body channel) and `hCh` (header channel)
// and writes contents to a file named `prefix`.go in directory `outDir`.
// After `bCh` is closed it awaits for a header contents from `hCh` and concats it with
// the body generated before. After this everything is dumped to the file.
func bufWriter(wg *sync.WaitGroup, bCh, hCh chan []byte, prefix, outDir string) {
var (
f *os.File
err error
bBuf, hBuf bytes.Buffer
)
defer wg.Done()
fName := filepath.Join(outputDirName, outDir, fmt.Sprintf("%s.go", prefix))
// Check if a target file exists and remove it if so
if checkFileExists(fName) {
if err := os.Remove(fName); err != nil {
logError(fmt.Errorf("file '%s' exists and can't be removed! Error: %s", fName, err))
return
}
logInfo(fmt.Sprintf("removed file: %s", fName))
}
// Open new file
if f, err = os.OpenFile(fName, os.O_CREATE|os.O_RDWR|os.O_SYNC, 0644); err != nil {
log.Fatal(err)
return
}
defer f.Close()
// listen for body and header channels
for {
body, bOk := <-bCh
bBuf.Write(body)
if !bOk {
break
}
}
header := <-hCh
// Add header on top of body buffer
hBuf.Write(header)
hBuf.Write(bBuf.Bytes())
bb := hBuf.Bytes()
// Format code && write to the file
if fmtCode, err := format.Source(bb); err != nil {
log.Printf("[[%s]] error formatting code: %s. Writing code as is...", fName, err)
if n, e := f.Write(bb); e != nil {
logError(fmt.Errorf("error writing %s: %s", fName, e))
} else {
logInfo(fmt.Sprintf("successfully written %d bytes (unformatted) to %s.", n, fName))
}
} else {
if n, e := f.Write(fmtCode); e != nil {
logError(fmt.Errorf("error writing %s: %s", fName, e))
} else {
logInfo(fmt.Sprintf("successfully written %d bytes to %s", n, fName))
}
}
}
// generateItems: walks againt `items` and runs rendering of each item
// sending rendered contents to an appropriate channel
func generateItems(items IIterator, hTmpl, bTmpl *template.Template, outDir string, prefixes map[string]struct{}, imports map[string]map[string]struct{}) {
bodyChans := createByteChannels(prefixes)
headChans := createByteChannels(prefixes)
wg := &sync.WaitGroup{}
wg.Add(len(bodyChans))
for k := range prefixes {
go bufWriter(wg, bodyChans[k], headChans[k], k, outDir)
}
for val, ok := items.Next(); ok; val, ok = items.Next() {
if buf, err := val.Render(bTmpl); err == nil {
bodyChans[getApiNamePrefix(items.GetKey())] <- buf
} else {
logError(err)
logError(err.(template.ExecError).Err)
}
}
for k := range prefixes {
hBuf := bytes.Buffer{}
close(bodyChans[k])
tmp := templateImports{
Imports: imports[k],
Prefix: k,
}
if err := hTmpl.Execute(&hBuf, tmp); err == nil {
headChans[k] <- hBuf.Bytes()
}
close(headChans[k])
}
wg.Wait()
}
// set of functions to check `IType` for belonging to a particular type
func IsString(t IType) bool {
return t.GetType() == schemaTypeString
}
func IsInt(t IType) bool {
return t.GetType() == schemaTypeInt
}
func IsBuiltin(t IType) bool {
return t.GetType() == schemaTypeBuiltin
}
func IsArray(t IType) bool {
return t.GetType() == schemaTypeArray
}
func IsObject(t IType) bool {
return t.GetType() == schemaTypeObject
}
func IsBoolean(t IType) bool {
return t.GetType() == schemaTypeBoolean
}
func IsInterface(t IType) bool {
return t.GetType() == schemaTypeInterface
}
func IsNumber(t IType) bool {
return t.GetType() == schemaTypeNumber
}
func IsMultiple(t IType) bool {
return t.GetType() == schemaTypeMultiple
}
// fullFuncs: returns a map of functions to be passed to a text template renderer
func fillFuncs(m map[string]interface{}) map[string]interface{} {
m["IsString"] = IsString
m["IsInt"] = IsInt
m["IsBuiltin"] = IsBuiltin
m["IsArray"] = IsArray
m["IsObject"] = IsObject
m["IsBoolean"] = IsBoolean
m["IsInterface"] = IsInterface
m["IsNumber"] = IsNumber
m["IsMultiple"] = IsMultiple
m["checkChars"] = checkChars
m["convertName"] = convertName
return m
}