-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
389 lines (353 loc) · 13.4 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
package main
import (
"bufio"
"bytes"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"github.com/fatih/color"
)
type Field struct {
Name string `json:"name"`
Value string `json:"value"`
}
type Block struct {
Type string `json:"type"`
Source string `json:"source"`
Rows []string `json:"rows"`
Fields []Field `json:"fields"`
Header string `json:"header"`
completed bool `json:"completed"`
}
func PrintBlock(block *Block) {
fmt.Println(" [Block Definition]")
fmt.Println(" Source: ", block.Source)
fmt.Println(" Type : ", block.Type)
fmt.Println(" Rows :")
for i, row := range block.Rows {
fmt.Println(" ", i, ":", row)
}
fmt.Println(" Fields:")
for i, field := range block.Fields {
fmt.Println(" ", i, ":(", field.Name, ":", field.Value, ")")
}
}
func main() {
version := "Version 0.002"
var blocks []Block
var keyValueStore [][]string
var inputFilePath string
var outputFilePath string
var keyValuePath string
var verboseOutput bool
var outputBlocks bool
var jsonOutFile string
var jsonAsInput bool
var jsonInputPath string
// flags declaration using flag package
flag.StringVar(&inputFilePath, "i", "source.txt", "path of the input file. Default is source.txt")
flag.StringVar(&outputFilePath, "o", "output.txt", "path of the output file. Default is output.txt")
flag.StringVar(&keyValuePath, "k", "keyvalue.csv", "path of the key-value store file as comma seperated file with two columns. Default is keyvalue.csv")
flag.BoolVar(&verboseOutput, "v", false, "activate verbose output to console")
flag.BoolVar(&outputBlocks, "outputjson", false, "activate output block definitions as JSON")
flag.StringVar(&jsonOutFile, "jsonoutfile", "blocksDefinitions.json", "set the output filepath of the block definitions JSON file")
flag.BoolVar(&jsonAsInput, "jsoninput", false, "activate using a JSON block definition from a file as input source")
flag.StringVar(&jsonInputPath, "jsoninfile", "blocksDefinitions.json", "use this file path if -jsoninput is set")
c := color.New(color.FgWhite).Add(color.Bold)
flag.Usage = func() {
fmt.Println("cst - the command shell template parser - ALPHA version", version, "\n") // redundant newline ok
fmt.Println(" cst -i <input filepath> -o <output filepath> [-k <key-value file path>] [-v]\n")
c.Println("DESCRIPTION")
fmt.Println("cst is a command line template parser that uses comma seperated files (csv) as it's data source.")
fmt.Println("It is being used to transform data, present in csv files, into structured text files,")
fmt.Println("such as HTML, JSON, XML or yaml files or any other structured file format.")
c.Println("ARGUMENTS")
fmt.Println("The program needs an input and an output file path.")
fmt.Println("All needed data file paths are being defined in the template file itself in so called block definitions")
fmt.Println("The input file defines the template for the output file.")
fmt.Println("All parsed template definitions are processed and written to the output file.\n")
fmt.Println("-i specifies the path of the input file")
fmt.Println("-o specifies the path of the output file")
c.Println("OPTIONS")
fmt.Println("-k if specified, cst uses the specified file path as the key value store file")
fmt.Println(" The key value store file is a csv file with two columns, where the first column")
fmt.Println(" defines the key and the second the value. Everything is a string.")
fmt.Println(" if -k is not specified, cst uses the definition in the source file. It has the following format:")
fmt.Println(" (store;source:<filepath>)")
fmt.Println(" This needs to be defined in its own text line with opening and closing brackets and the keyword 'store'")
fmt.Println("-v Activate verbose output to the console.")
fmt.Println(" This prints out all actions of the parser and the templating engine so that you can debug your template.")
}
flag.Parse()
// TODO: make all variables available through command arguments
// verbosity
// Optional: token delimiter like '{{}}'
if !jsonAsInput {
// the blocks structure will be created using the parser
file, err := os.Open(inputFilePath)
if err != nil {
fmt.Println("Error opening source file", inputFilePath, " Error Description: ", err)
os.Exit(1)
}
defer file.Close()
if verboseOutput {
c.Println("[Parser] Start on input file: ", inputFilePath)
}
var currentBlock *Block
var rowIndex int32 = 0
scanner := bufio.NewScanner(file)
// optionally, resize scanner's capacity for lines over 64K, see next example
for scanner.Scan() {
if verboseOutput {
fmt.Println("Scanning row index ", rowIndex)
}
row := scanner.Text()
if strings.HasPrefix(row, "(block-start;") {
if strings.HasSuffix(row, ")") { // found header of a block
if currentBlock != nil && currentBlock.completed == false {
fmt.Println("Error (block-start) without closing current block definition. Row[", rowIndex, "]:", row)
panic(1)
}
block := Block{}
block.Header = row
strHeader := strings.TrimPrefix(row, "(block-start;")
strHeader = strings.TrimSuffix(strHeader, ")")
fields := strings.Split(strHeader, ";")
for i, strField := range fields { // range over name:value definitions and add them to the structs Fields array
fieldTokens := strings.Split(strField, ":")
if len(fieldTokens) == 2 {
field := Field{Name: fieldTokens[0], Value: fieldTokens[1]}
if field.Name == "source" {
block.Source = field.Value
} else if field.Name == "type" {
block.Type = field.Value
}
block.Fields = append(block.Fields, field)
} else {
fmt.Println("Error in block header definition. Cannot read field definition, field index [", i, "] Row[", rowIndex, "]:", row)
panic(1)
}
}
blocks = append(blocks, block)
currentBlock = &blocks[len(blocks)-1]
} else {
// error in defining a block header, report error and panic
fmt.Println("Error in defining a blocks header. Row[", rowIndex, "]:", row)
panic(1)
}
} else if strings.Compare(row, "(block-end)") == 0 { // found block-end
if currentBlock != nil {
currentBlock.completed = true
if verboseOutput {
PrintBlock(currentBlock)
}
currentBlock = nil
} else {
fmt.Println("Error (block-end) without (block-start). Row[", rowIndex, "]:", row)
panic(1)
}
} else if strings.HasPrefix(row, "(store;") {
if strings.HasSuffix(row, ")") {
if currentBlock != nil && currentBlock.completed == false {
fmt.Println("Error (store) definition started without closing current block definition. Row[", rowIndex, "]:", row)
panic(1)
}
// key-value store definition found
block := Block{}
block.Header = row
block.Type = "store"
strHeader := strings.TrimPrefix(row, "(store;") // Todo: DUPLICATE CODE - MAKE FUNCTION!!
strHeader = strings.TrimSuffix(strHeader, ")")
fields := strings.Split(strHeader, ";")
for i, strField := range fields { // range over name:value definitions and add them to the structs Fields array
fieldTokens := strings.Split(strField, ":")
if len(fieldTokens) == 2 {
field := Field{Name: fieldTokens[0], Value: fieldTokens[1]}
if field.Name == "source" {
block.Source = field.Value
}
block.Fields = append(block.Fields, field)
} else {
fmt.Println("Error in block header definition. Cannot read field definition, field index [", i, "] Row[", rowIndex, "]:", row)
panic(1)
}
}
blocks = append(blocks, block)
if verboseOutput {
PrintBlock(&block)
}
currentBlock = nil
// finished with store block
} else {
fmt.Println("Error (store) definition started but not closed. Closing bracket is needed! Row[", rowIndex, "]:", row)
panic(1)
}
} else {
// anything else is a template definition of the block
// it will be added to the Rows array of the currentBlock
if currentBlock == nil {
block := Block{}
block.Rows = append(block.Rows, row)
block.Type = "string"
block.completed = true
blocks = append(blocks, block)
currentBlock = &blocks[len(blocks)-1]
if verboseOutput {
PrintBlock(currentBlock)
}
currentBlock = nil
} else {
currentBlock.Rows = append(currentBlock.Rows, row)
}
}
rowIndex++
}
file.Close()
if verboseOutput {
c.Println("[Parser] Done\n")
}
// write the blocks definition structure out to a JSON file for further use
if outputBlocks {
var buffer bytes.Buffer
e := json.NewEncoder(&buffer)
e.SetEscapeHTML(false)
e.SetIndent("", " ")
e.Encode(blocks)
_ = ioutil.WriteFile(jsonOutFile, buffer.Bytes(), 0644)
}
} else {
// the blocks structure will be created using unmarshalling JSON from a file
jsonInputBuffer, err := ioutil.ReadFile(jsonInputPath)
if err != nil {
fmt.Println("Error while reading JSON file ", jsonInputPath)
os.Exit(1)
}
err = json.Unmarshal(jsonInputBuffer, &blocks)
if err != nil {
fmt.Println("Error while unmarshalling JSON block definition from ", jsonInputPath)
os.Exit(1)
}
}
// Now loop over the blocks and work them out
// write into a buffer that then is going to be appended to an output file
outputFile, err := os.Create(outputFilePath)
if err != nil {
log.Fatal(err)
}
if verboseOutput {
c.Println("[Template Engine] Start on output file: ", outputFilePath)
}
for i := 0; i < len(blocks); i++ {
// verbose output
if verboseOutput {
fmt.Print("Parsing block #", i, " type=", blocks[i].Type, " rows=", blocks[i].Rows)
}
if blocks[i].Type == "string" {
// 1.) basic string from row in source file
outputStr := blocks[i].Rows[0] + "\n"
// 2.) Key-Value Templating
// {{key}}
for _, key := range keyValueStore {
// really dumb method now to loop over all keys but it will do for the first implementation
// Todo: Performance enhancement here!!
token := "{{" + key[0] + "}}"
outputStr = strings.Replace(outputStr, token, key[1], -1) // replace {index} with the column nr=index
}
outputFile.WriteString(outputStr)
if verboseOutput {
fmt.Println(" -> written to output file.")
}
} else if blocks[i].Type == "store" {
// key-store definition
// read the csv file and use it as a key value store for all tokens
if blocks[i].Source != "" {
sourceFile, err := os.Open(blocks[i].Source)
if err != nil {
fmt.Println("Error while opening the source file: ", err)
panic(1)
}
reader := csv.NewReader(sourceFile)
reader.Comma = ','
reader.Comment = '#'
keyValueStore, err = reader.ReadAll()
if err != nil {
fmt.Println("Error: Could not read the csv file. Description: ", err)
panic(1)
}
// key value store is present in the variable keyValueStore
// verbose output
if verboseOutput {
fmt.Println(" -> Key-Value store successfully read: ", keyValueStore)
}
} else {
fmt.Println("Error: Cannot read key value store fields as the source definition is not set. Check the (store ..) definition in the defintiion file..")
panic(1)
}
} else if blocks[i].Type == "foreach" {
// foreach block definition
// 1.) open source file
if verboseOutput {
fmt.Println("")
}
block := &blocks[i]
if block.Source != "" {
sourceFile, err := os.Open(block.Source)
if err != nil {
fmt.Println("Error while opening the source file: ", err)
panic(1)
}
reader := csv.NewReader(sourceFile)
reader.Comma = ','
reader.Comment = '#'
records, _ := reader.ReadAll()
//fmt.Println("Records in file ", block.Source, ": ", records)
for recordIndex, record := range records {
// per record ...
// loop over all Rows of the current definition block
for rowIndex, blockRow := range block.Rows {
// 1.) column-index Templating
// {column-index}
// replace in Row string all occurrences of columns in the current csv record
outputStr := blockRow
for indexColumn, column := range record {
// for every column, replace the {column-index} with its content in the current record
token := "{" + strconv.Itoa(indexColumn) + "}"
outputStr = strings.Replace(outputStr, token, column, -1) // replace {index} with the column nr=index
if indexColumn == (len(record) - 1) {
// verbose output
if verboseOutput {
fmt.Println(" Replacing for record #", recordIndex, " with record='", record, "' in row #", rowIndex, "='"+blockRow, " output='", outputStr, "'")
}
// last column, add newline character
outputStr = outputStr + "\n"
}
}
// 2.) Key-Value Templating
// {{key}}
for _, key := range keyValueStore {
// really dumb method, currently, to loop over all keys but it will do for the first implementation
// Todo: Performance enhancement here!!
token := "{{" + key[0] + "}}"
outputStr = strings.Replace(outputStr, token, key[1], -1) // replace {index} with the column nr=index
}
// write the Row to the output file
outputFile.WriteString(outputStr)
}
}
if verboseOutput {
fmt.Println(" -> written to output file.")
}
sourceFile.Close()
} else {
fmt.Println("Error: Foreach block does not have a source definition. Please add the source of the csv file in the \"source\" field. Definition:", block.Fields)
panic(1)
}
}
}
}