-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconf.go
135 lines (118 loc) · 2.55 KB
/
conf.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
package main
import (
"bytes"
"flag"
"log"
"os"
"regexp"
"github.com/rogpeppe/rjson"
)
const baseConfiguration = `{
"Dataset" : {},
"Reader" : {
"Method" : "Delimited",
"Separator" : "",
"CountSeparator" : "",
"Skip" : ""
},
"Extension" : {
"Method" : "",
"Groups" : {},
"Extendable" : {},
"Outputtable" : {}
},
"Output" : {
"Method" : "Sorted",
"Count" : -1
},
"Print" : {
"ShowHeader" : true
}
}`
type FileGroup struct {
File string
Files []string
FileList string
}
type Conf struct {
Dataset map[string]FileGroup
Reader struct {
Method string
Separator string
CountSeparator string
Skip string
}
Extension struct {
Method string
Groups map[string]struct{ Elements string }
Extendable map[string]rjson.RawMessage
Outputtable map[string]rjson.RawMessage
}
Output struct {
Method string
SortBy []string
Count int
}
Printer struct {
Method string
ShowHeader bool
Reverse bool
Header string
Format string
}
}
func (conf *Conf) WriteToFile(filename string) {
file, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
enc := rjson.NewEncoder(file)
if err = enc.Encode(&conf); err != nil {
log.Fatal(err)
}
}
func readBaseConfiguration(config string) *Conf {
conf := &Conf{}
dec := rjson.NewDecoder(bytes.NewBufferString(config))
if err := dec.Decode(conf); err != nil {
log.Println("Error in base configuration")
log.Fatal(err)
}
return conf
}
func NewConf(configFile string) *Conf {
conf := readBaseConfiguration(baseConfiguration)
if configFile == "" {
return conf
}
data, err := os.ReadFile(configFile)
if err != nil {
log.Println("Unable to read configuration file: ", configFile)
log.Fatal(err)
}
regArg := regexp.MustCompile(`^\s*(.*)=(.*)$`)
for _, arg := range flag.Args() {
if !regArg.MatchString(arg) {
log.Fatal("Argument was not in correct form: ", arg)
}
tokens := regArg.FindStringSubmatch(arg)
replace := regexp.MustCompile(`\$` + tokens[1] + `(=[^$]*)?\$`)
replacement := ([]byte)(tokens[2])
data = replace.ReplaceAll(data, replacement)
}
regDefaults := regexp.MustCompile(`\$[^\$]+\$`)
regDefault := regexp.MustCompile(`\$[^=]+=(.*)\$`)
data = regDefaults.ReplaceAllFunc(data, func(repl []byte) []byte {
defaults := regDefault.FindSubmatch(repl)
if defaults != nil {
return defaults[1]
}
return nil
})
dec := rjson.NewDecoder(bytes.NewReader(data))
if err = dec.Decode(conf); err != nil {
log.Println("Error in configuration file: ", configFile)
log.Fatal(err)
}
return conf
}