-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
493 lines (411 loc) · 10.3 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
)
const packageTemplate = `package kurento
{{ .Content }}
`
const strTemplate = `
{{ define "Arguments" }}{{ range $i, $e := .Params }}{{ if $i }} , {{ end }}{{ $e.name }} {{ $e.type | checkElement }}{{ end }}{{ end }}
{{ $name := .Name}}
{{/* Generator interface then struct */}}
{{ if ne .Name "MediaObject" }}
type I{{ .Name }} interface {
{{ range .Methods }}
{{ .Name | title }}({{ template "Arguments" .}})({{ if .Return.type }}{{ .Return.type }},{{ end }} error)
{{ end }}
}
{{ end }}
{{ .Doc }}
type {{ .Name }} struct {
{{ if eq .Name "MediaObject" }}connection *Connection
{{ else }} {{ .Extends }}
{{ end }}
{{ range .Properties }}
{{ .doc }}
{{ .name | title }} {{ .type }}
{{ end }}
}
// Return Constructor Params to be called by "Create".
func (elem *{{ .Name }}) getConstuctorParams(from IMediaObject, options map[string]interface{}) map[string]interface{} {
{{ if len .Constructor.Params }}
// Create basic constructor params
ret := map[string]interface{} {
{{ range .Constructor.Params }}{{ if eq .type "string" "float64" "boolean" "int" }}"{{ .name }}" : {{ .defaultValue }},
{{ else }} "{{ .name }}" : fmt.Sprintf("%s", from),
{{ end }}{{ end }}
}
mergeOptions(ret, options)
return ret
{{ else }}return options
{{ end }}
}
{{ range .Methods }}
{{ .Doc }}
{{ if .Return.doc }}
// Returns
{{ .Return.doc }}
{{ end }}
func (elem *{{$name}}) {{ .Name | title }}({{ template "Arguments" . }}) ({{ if .Return.type }}{{ .Return.type }}, {{ end}} error) {
req := elem.getInvokeRequest()
{{ if .Params }}
params := make(map[string]interface{})
{{ range .Params }}
setIfNotEmpty(params, "{{ .name }}", {{ .name }})
{{end}}
{{ end }}
req["params"] = map[string]interface{} {
"operation": "{{ .Name }}",
"object": elem.Id,
{{ if .Params }}
"operationParams": params,
{{ end }}
}
// call server and and wait response
response := <-elem.connection.Request(req)
{{ if .Return }}
{{ .Return.doc }}
{{ if eq .Return.type "string" "int" "float64" "boolean" }}
return response.Result["value"], response.Error
{{ else }}
ret := {{ .Return.type }}{}
return ret, response.Error
{{ end }}
{{ else }}
return response.Error
{{ end }}
}
{{ end }}
`
const complexTypeTemplate = `
{{ if eq .TypeFormat "ENUM" }}
{{ $name := .Name }}
{{ .Doc }}
type {{.Name}} string
// Implement fmt.Stringer interface
func (t {{.Name}}) String() string {
return string(t)
}
const (
{{ range .Values }}
{{ $name | uppercase }}_{{ . | uppercase}} {{ $name }} = "{{ . }}"
{{ end}}
)
{{ else }}
type {{ .Name }} struct {
{{ range .Properties}}{{ .name | title }} {{ .type }}
{{ end }}
}
{{ end }}
`
const DOCLINELENGTH = 79
var re = regexp.MustCompile(`(.+)\[\]`)
var symbol = regexp.MustCompile(`<>`)
var CPXTYPES []string
type Core struct {
RemoteClasses []Class
ComplexTypes []ComplexType
}
type Class struct {
Name string
Doc string
Abstract bool
Properties []map[string]interface{}
Extends string
Methods []Method
Events []string
Constructor Constructor
}
type Constructor struct {
Name string
Doc string
Params []map[string]interface{}
}
type Method struct {
Constructor
Return map[string]interface{}
}
type ComplexType struct {
TypeFormat string
Doc string
Values []string
Name string
Properties []map[string]interface{}
}
// template func that change Mediaxxx to IMediaxxx to be
// sure to work with interface.
// Set it global to be used by funcMap["paramValue"] above.
func tplCheckElement(p string) string {
if len(p) > 5 && p[:5] == "Media" {
if p[len(p)-4:] != "Type" {
return "IMedia" + p[5:]
}
}
return p
}
func isComplexType(t string) bool {
for _, c := range CPXTYPES {
if c == t {
return true
}
}
return false
}
var funcMap = template.FuncMap{
"title": strings.Title,
"uppercase": strings.ToUpper,
"checkElement": tplCheckElement,
"paramValue": func(p map[string]interface{}) string {
name := p["name"].(string)
t := p["type"].(string)
t = tplCheckElement(t)
ctype := isComplexType(t)
switch t {
case "float64", "int":
return fmt.Sprintf("\"%s\" = %s", name, name)
case "string", "boolean":
return fmt.Sprintf("\"%s\" = %s", name, name)
default:
if !ctype && t[0] == 'I' {
return fmt.Sprintf("\"%s\" = fmt.Sprintf(\"%%s\", %s)", name, name)
}
}
return fmt.Sprintf("\"%s\" = %s", name, name)
},
}
func parseComplexTypes(complexs []string, suffix string) {
var paths []string
// save kmds file to paths
for _, path := range complexs {
pathList, err := filepath.Glob(path)
if err != nil {
logFatal(err)
}
paths = append(paths, pathList...)
}
// parse
var ret []string
for _, path := range paths {
ctypes := getModel(path).ComplexTypes
if ctypes == nil {
continue
}
for _, ctype := range ctypes {
CPXTYPES = append(CPXTYPES, ctype.Name)
ctype.Doc = formatDoc(ctype.Doc)
for i, p := range ctype.Properties {
ctype.Properties[i] = formatTypes(p)
}
buff := bytes.NewBufferString("")
tpl, err := template.New("complexttypes").Funcs(funcMap).Parse(complexTypeTemplate)
if err != nil {
}
tpl.Execute(buff, ctype)
ret = append(ret, buff.String())
}
writeFile(createFile(path, suffix), ret)
}
}
func parseRemotes(remotes []string) {
var paths []string
// save kmds file to paths
for _, path := range remotes {
pathList, err := filepath.Glob(path)
if err != nil {
logFatal(err)
}
paths = append(paths, pathList...)
}
for _, p := range paths {
c := getModel(p).RemoteClasses
ret := make([]string, len(c))
for idx, cl := range c {
fmt.Println("Generating ", cl.Name)
for j, p := range cl.Properties {
p = formatTypes(p)
switch p["type"] {
case "string", "float64", "bool", "[]string":
default:
if _, ok := p["type"].(string); ok {
if p["type"].(string)[:2] == "[]" {
t := p["type"].(string)[2:]
if isComplexType(t) {
p["type"] = "[]*" + t
} else {
p["type"] = "[]I" + t
}
} else {
if isComplexType(p["type"].(string)) {
p["type"] = "*" + p["type"].(string)
} else {
p["type"] = "I" + p["type"].(string)
}
}
}
}
cl.Properties[j] = p
}
for j, m := range cl.Methods {
for i, p := range m.Params {
p := formatTypes(p)
m.Params[i] = p
}
m.Doc = formatDoc(m.Doc)
if m.Return["type"] != nil {
m.Return = formatTypes(m.Return)
m.Return["doc"] = formatDoc(m.Return["doc"].(string))
}
cl.Methods[j] = m
}
for j, p := range cl.Constructor.Params {
p := formatTypes(p)
cl.Constructor.Params[j] = p
}
tpl, err := template.New("structure").Funcs(funcMap).Parse(strTemplate)
if err != nil {
logFatal(err)
}
buff := bytes.NewBufferString("")
cl.Doc = formatDoc(cl.Doc)
err = tpl.Execute(buff, cl)
if err != nil {
logFatal(err)
}
ret[idx] = buff.String()
}
writeFile(createFile(p, ""), ret)
}
}
func formatDoc(doc string) string {
doc = strings.Replace(doc, ":rom:cls:", "", -1)
doc = strings.Replace(doc, ":term:", "", -1)
doc = strings.Replace(doc, "``", `"`, -1)
doc = strings.Replace(doc, "/*", "", -1)
doc = strings.Replace(doc, "*/", "", -1)
lines := strings.Split(doc, "\n")
var part []string
for _, line := range lines {
part = append(part, line)
}
for i, p := range part {
part[i] = "/*" + strings.TrimSpace(p) + "*/"
}
return strings.Join(part, "\n")
}
func formatTypes(p map[string]interface{}) map[string]interface{} {
p["doc"] = formatDoc(p["doc"].(string))
if p["type"] == "String[]" {
p["type"] = "[]string"
}
if p["type"] == "String" || p["type"] == "String<>" {
p["type"] = "string"
}
if p["type"] == "float" || p["type"] == "double" {
p["type"] = "float64"
}
if p["type"] == "boolean" {
p["type"] = "bool"
}
// type
if re.MatchString(p["type"].(string)) {
found := re.FindAllStringSubmatch(p["type"].(string), -1)
p["type"] = "[]" + found[0][1]
}
// expect <>
if symbol.MatchString(p["type"].(string)) {
substr := p["type"].(string)
p["type"] = substr[0 : len(substr)-2]
}
// default value
if p["defaultValue"] == "" || p["defaultValue"] == nil {
switch p["type"] {
case "string":
p["defaultValue"] = `""`
case "bool":
p["defaultValue"] = "false"
case "int", "float64":
p["defaultValue"] = "0"
}
}
return p
}
func getModel(path string) Core {
i := Core{}
data, err := ioutil.ReadFile(path)
if err != nil {
logFatal(err)
}
str := strings.Replace(string(data), "\n", " ", -1)
err = json.Unmarshal([]byte(str), &i)
if err != nil {
logFatal(err)
}
return i
}
func writeFile(path string, classess []string) {
content := strings.Join(classess, "\n")
tpl, _ := template.New("package").Parse(packageTemplate)
buff := bytes.NewBufferString("")
tpl.Execute(buff, map[string]string{
"Content": content,
})
ioutil.WriteFile(path, buff.Bytes(), os.ModePerm)
}
func createFile(path string, suffix string) string {
base := filepath.Base(path)
base = strings.Replace(base, ".kmd.json", "", -1)
base = strings.Replace(base, ".", "_", -1)
base = "kurento/" + base
if suffix != "" {
base += "_" + suffix + ".go"
} else {
base += ".go"
}
return strings.ToLower(base)
}
func logFatal(err error) {
log.Fatal(err)
}
func main() {
// Write base data to dst
data, err := ioutil.ReadFile("kurento_go_base/base.go")
if err != nil {
logFatal(err)
}
err = ioutil.WriteFile("kurento/base.go", data, os.ModePerm)
if err != nil {
logFatal(err)
}
// write ws data to dst
data, err = ioutil.ReadFile("kurento_go_base/kurento_ws.go")
if err != nil {
logFatal(err)
}
err = ioutil.WriteFile("kurento/kurento_ws.go", data, os.ModePerm)
if err != nil {
logFatal(err)
}
// ComplexTypes list
complexList := []string{
"kms-core/src/server/interface/core.kmd.json",
"kms-elements/src/server/interface/elements.*.kmd.json",
"kms-filters/src/server/interface/filters.*.kmd.json",
}
parseComplexTypes(complexList, "complext_types")
// RemoteClasses list
remoteList := []string{
"kms-core/src/server/interface/core.kmd.json",
"kms-elements/src/server/interface/elements.*.kmd.json",
"kms-filters/src/server/interface/filters.*.kmd.json",
}
parseRemotes(remoteList)
}