-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathutils.go
296 lines (230 loc) · 6.27 KB
/
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
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
package kolpa
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
// Parses and replaces tags in a text with provided values in the map m.
func (g *Generator) parser(text string, m map[string]string) string {
src := []byte(text)
search := regexp.MustCompile(`{{(.*?)}}`)
src = search.ReplaceAllFunc(src, func(s []byte) []byte {
return []byte(m[string(s)[2:len(s)-2]])
})
return string(src)
}
// Parses and replaces tags in a text with provided values in the map m.
func (g *Generator) nparser(text string, m map[int]string) string {
src := []byte(text)
search := regexp.MustCompile(`{{(.*?)}}`)
c := 0
src = search.ReplaceAllFunc(src, func(s []byte) []byte {
res := []byte(m[c])
c++
return res
})
return string(src)
}
// Concatenates multiple string slices by using append function and returns new slice.
func appendMultiple(slices ...[]string) []string {
base := slices[0]
rest := slices[1:]
for _, slice := range rest {
base = append(base, slice...)
}
return base
}
// Concatenates a slice of string slices into a string slice
func (g *Generator) appendMultipleWithSlice(slices []string) ([]string, error) {
var result [][]string
var slice []string
var err error
for _, v := range slices {
slice, err = g.fileToSlice(v)
if err != nil {
return nil, err
}
result = append(result, slice)
}
base := result[0]
rest := result[1:]
for _, slice := range rest {
base = append(base, slice...)
}
return base, nil
}
// Takes format and outputs the needed variables for the format
// Sample input: `{{prefix_female}} {{female_first_name}}`
// Sample output: [ prefix_female female_first_name ]
func (g *Generator) formatToSlice(format string) []string {
re := regexp.MustCompile(`{{(.*?)}}`)
find := re.FindAllStringSubmatch(format, -1)
res := []string{}
for _, v := range find {
res = append(res, v[1])
}
return res
}
// Reads the file "fName" and returns its content as a slice of strings.
func (g *Generator) fileToSlice(fName string) ([]string, error) {
var res []string
path := getCurrentDir() + "/data/" + g.Locale_ + "/" + fName
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
res = append(res, scanner.Text())
}
if err := scanner.Err(); err != nil {
//log.Println("Inteded generation is not valid for selected language. Switching to en_US.")
g.Locale_ = "en_US"
return g.fileToSlice(fName)
}
return res, nil
}
// Reads the all files starting with "fName" and returns their content as a slice of strings.
func (g *Generator) fileToSliceAll(fName string) ([]string, error) {
var res []string
var err error
var file *os.File
path := getCurrentDir() + "/data/" + g.Locale_ + "/"
f, err := os.Open(path)
if err != nil {
return nil, err
}
l, err := f.Readdirnames(-1)
if err != nil {
return nil, err
}
fNames := l[:0]
for _, x := range l {
if strings.HasPrefix(x, fName) {
fNames = append(fNames, x)
}
}
for _, name := range fNames {
file, err = os.Open(path + name)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
res = append(res, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
}
if len(res) == 0 {
return nil, fmt.Errorf("Length is zero.")
}
return res, nil
}
// Returns random item from the given string slice.
func getRandom(options []string) string {
rand.Seed(time.Now().UTC().UnixNano())
return options[rand.Intn(len(options))]
}
// Returns random boolean variable.
func randBool() bool {
rand.Seed(time.Now().UTC().UnixNano())
val := rand.Float64()
return parseRandomToBoolean(val)
}
// getCurrentDir - Get dir path to current file (utils.go)
func getCurrentDir() string {
_, filePath, _, _ := runtime.Caller(1)
return filepath.Dir(filePath)
}
// Returns all possible data for languages.
func getLanguages() []string {
path := getCurrentDir() + "/data/"
files, _ := ioutil.ReadDir(path)
var n string
var res []string
for _, f := range files {
n = string(f.Name())
if string(n[0]) != "." {
res = append(res, f.Name())
}
}
return res
}
// Returns if given file is contains parseable content or not.
func (g *Generator) isParseable(sl string) bool {
if len(sl) == 0 {
return false
}
re := regexp.MustCompile(`{{(.*?)}}`)
if match := re.FindString(sl); len(match) > 0 {
return true
}
return false
}
// Returns if given file contains content that needs to be replaced with numeric values.
func (g *Generator) isNumeric(sl []string) bool {
if len(sl) == 0 {
return false
}
re := regexp.MustCompile(`##(.*?)##`)
if match := re.FindString(sl[0]); len(match) > 0 {
return true
}
return false
}
// Generates an integer with given digit length and greater than or equal and less than parameters
func (g *Generator) numericRandomizer(args []string) string {
length, err := strconv.Atoi(args[0])
gte, err2 := strconv.Atoi(args[1])
lt, err3 := strconv.Atoi(args[2])
if err != nil && err2 != nil && err3 != nil {
return "something is wrong with arguments of numeric randomizer function"
}
var buffer bytes.Buffer
for i := 0; i < length; i++ {
buffer.WriteString(strconv.Itoa(int(g.numBetween(gte, lt))))
}
return buffer.String()
}
// Generates a random integer between given greater than or equal and less than parameters
func (g *Generator) numBetween(gte int, lt int) int32 {
return rand.Int31n(int32(lt)-int32(gte)) + int32(gte)
}
// Determines the type of given token. It should be whether func or default.
func (g *Generator) typeOfToken(token string) string {
if token[0] == '%' && token[len(token)-1] == '%' {
return "func"
} else if token[0:4] == "same" {
return "same"
}
return "default"
}
// Calls DateTimeAfterWithString function and returns its Stringer method.
// This function is specifically written for in format function calls.
func (g *Generator) userAgentDateAfter(args []string) string {
return g.DateFormatter("2006-01-02 15:04:05", g.DateTimeAfterWithString(args[0]).UTC().String())
}
func mapLine(line []string, data map[string]string) {
if len(line) > 1 {
data[line[0]] = line[1]
}
}
func parseRandomToBoolean(val float64) bool {
if val <= 0.5 {
return true
}
return false
}