-
Notifications
You must be signed in to change notification settings - Fork 1
/
action.go
105 lines (92 loc) · 2.52 KB
/
action.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
package main
import (
"bytes"
"database/sql"
"encoding/json"
"io"
"io/ioutil"
"os"
"github.com/go-yaml/yaml"
"github.com/sirkon/gosrcfmt"
"github.com/sirkon/gotify"
"github.com/sirkon/message"
"github.com/sirkon/ch-encode/internal/generator"
"github.com/sirkon/ch-encode/internal/generator/chstuff"
"github.com/sirkon/ch-encode/internal/generator/gogen"
"github.com/sirkon/ch-encode/internal/util"
)
func yamlSource(path string) map[string]string {
res := map[string]string{}
data, err := ioutil.ReadFile(path)
if err != nil {
message.Criticalf("Cannot read `%s`: %s", path, err)
}
if err := yaml.Unmarshal(data, &res); err != nil {
message.Criticalf("Cannot parse `%s` as YAML file: %s", path, err)
}
return res
}
func jsonSource(path string) map[string]string {
res := map[string]string{}
data, err := ioutil.ReadFile(path)
if err != nil {
message.Criticalf("Cannot read `%s`: %s", path, err)
}
if err := json.Unmarshal(data, &res); err != nil {
message.Criticalf("Cannot parse `%s` as JSON file: %s", path, err)
}
return res
}
func action(isTesting bool, yamlDict string, jsonDict string, dateField string, tables []string, connParams string) error {
var dict map[string]string
if len(yamlDict) > 0 {
dict = yamlSource(yamlDict)
}
if len(jsonDict) > 0 {
dict = jsonSource(jsonDict)
}
goish := gotify.New(dict)
prms := util.EnvCHParams(connParams)
connect, err := sql.Open("clickhouse", prms.DBURL())
if err != nil {
panic(err)
}
for _, table := range tables {
metas, err := chstuff.RetrieveTableMeta(connect, table)
if err != nil {
message.Critical(err)
}
partWriter := &bytes.Buffer{}
gen := gogen.New(table, goish, partWriter)
fields := generator.NewFieldSet(gen)
dateArg := func(gen generator.Generator) string { return "" }
for _, meta := range metas {
fieldInfo := chstuff.Meta2Field(meta)
if meta.Name == dateField {
dateArg = func(gen generator.Generator) string { return fieldInfo.ArgName(gen) }
}
fields.Add(fieldInfo)
}
if err = generator.Generate(gen, dateArg, fields); err != nil {
message.Critical(err)
}
writer := &bytes.Buffer{}
var output io.WriteCloser
if isTesting {
output = os.Stdout
} else {
output, err = GoModule(goish, table)
if err != nil {
message.Critical(err)
}
}
gen.Header(writer)
io.Copy(writer, partWriter)
gosrcfmt.FormatReader(output, writer)
if err = output.Close(); err != nil {
message.Critical(err)
}
message.Noticef("Table `\033[1m%s\033[0m` encoder generated", table)
}
return nil
}