-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathhelper.go
369 lines (319 loc) · 7.55 KB
/
helper.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
package core
import (
"archive/zip"
"bufio"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/mitchellh/go-homedir"
)
// GetFileContent reads file and returns its content.
func GetFileContent(filename string) string {
var result strings.Builder
if strings.Contains(filename, "~") {
var err error
filename, err = homedir.Expand(filename)
if err != nil {
return ""
}
}
file, err := os.Open(filename)
if err != nil {
return ""
}
defer file.Close()
// Create a buffer to store file content
buf := make([]byte, 1024)
// Read file content into the buffer
for {
n, err := file.Read(buf)
if err != nil && err != io.EOF {
return ""
}
if n == 0 {
break
}
result.Write(buf[:n])
}
return result.String()
}
// ReadingFile Reading file and return content as []string
func ReadingFile(filename string) []string {
var result []string
if strings.HasPrefix(filename, "~") {
filename, _ = homedir.Expand(filename)
}
file, err := os.Open(filename)
defer file.Close()
if err != nil {
return result
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
val := scanner.Text()
result = append(result, val)
}
if err := scanner.Err(); err != nil {
return result
}
return result
}
// ReadingFileUnique Reading file and return content as []string
func ReadingFileUnique(filename string) []string {
var result []string
if strings.Contains(filename, "~") {
filename, _ = homedir.Expand(filename)
}
file, err := os.Open(filename)
defer file.Close()
if err != nil {
return result
}
unique := true
seen := make(map[string]bool)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
val := scanner.Text()
// unique stuff
if val == "" {
continue
}
val = strings.TrimSpace(val)
if seen[val] && unique {
continue
}
if unique {
seen[val] = true
result = append(result, val)
}
}
if err := scanner.Err(); err != nil {
return result
}
return result
}
// WriteToFile write string to a file
func WriteToFile(filename string, data string) (string, error) {
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return "", err
}
defer file.Close()
_, err = io.WriteString(file, data+"\n")
if err != nil {
return "", err
}
return filename, file.Sync()
}
// Unique unique content of a file and remove blank line
func Unique(filename string) {
if filename == "" {
return
}
DebugF("Unique Output: %v", filename)
data := ReadingFileUnique(filename)
WriteToFile(filename, strings.Join(data, "\n"))
}
// AppendToContent append string to a file
func AppendToContent(filename string, data string) (string, error) {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return "", err
}
if _, err := f.Write([]byte(data + "\n")); err != nil {
return "", err
}
if err := f.Close(); err != nil {
return "", err
}
return filename, nil
}
// FileExists check if file is exist or not
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// FolderExists check if file is exist or not
func FolderExists(foldername string) bool {
if _, err := os.Stat(foldername); os.IsNotExist(err) {
return false
}
return true
}
// GetFileNames get all file name with extension
func GetFileNames(dir string, ext string) []string {
if _, err := os.Stat(dir); os.IsNotExist(err) {
return nil
}
var files []string
filepath.Walk(dir, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() {
if strings.HasSuffix(f.Name(), ext) {
filename, _ := filepath.Abs(path)
files = append(files, filename)
}
}
return nil
})
return files
}
// IsJSON check if string is JSON or not
func IsJSON(str string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
}
// GetTS get current timestamp and return a string
func GetTS() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
// GenHash gen SHA1 hash from string
func GenHash(text string) string {
h := sha1.New()
h.Write([]byte(text))
hashed := h.Sum(nil)
return fmt.Sprintf("%x", hashed)
}
// Unzip will decompress a zip archive, moving all files and folders
// within the zip file (parameter 1) to an output directory (parameter 2).
func Unzip(src string, dest string) ([]string, error) {
var filenames []string
r, err := zip.OpenReader(src)
if err != nil {
return filenames, err
}
defer r.Close()
for _, f := range r.File {
// Store filename/path for returning and using later on
fpath := filepath.Join(dest, f.Name)
if !strings.HasPrefix(fpath, filepath.Clean(dest)+string(os.PathSeparator)) {
return filenames, fmt.Errorf("%s: illegal file path", fpath)
}
filenames = append(filenames, fpath)
if f.FileInfo().IsDir() {
// Make Folder
os.MkdirAll(fpath, os.ModePerm)
continue
}
// Make File
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return filenames, err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return filenames, err
}
rc, err := f.Open()
if err != nil {
return filenames, err
}
_, err = io.Copy(outFile, rc)
// Close the file without defer to close before next iteration of loop
outFile.Close()
rc.Close()
if err != nil {
return filenames, err
}
}
return filenames, nil
}
// ExpandLength make slice to length
func ExpandLength(list []string, length int) []string {
c := []string{}
for i := 1; i <= length; i++ {
c = append(c, list[i%len(list)])
}
return c
}
// StartWithNum check if string start with number
func StartWithNum(raw string) bool {
r, err := regexp.Compile("^[0-9].*")
if err != nil {
return false
}
return r.MatchString(raw)
}
// StripPath just strip some invalid string path
func StripPath(raw string) string {
raw = strings.Replace(raw, "/", "_", -1)
raw = strings.Replace(raw, " ", "_", -1)
return raw
}
// Base64Encode just Base64 Encode
func Base64Encode(raw string) string {
return base64.StdEncoding.EncodeToString([]byte(raw))
}
// Base64Decode just Base64 Encode
func Base64Decode(raw string) string {
data, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
return raw
}
return string(data)
}
// URLDecode decode url
func URLDecode(raw string) string {
decodedValue, err := url.QueryUnescape(raw)
if err != nil {
return raw
}
return decodedValue
}
// URLEncode Encode query
func URLEncode(raw string) string {
decodedValue := url.QueryEscape(raw)
return decodedValue
}
// GenPorts gen list of ports based on input
func GenPorts(raw string) []string {
var ports []string
if strings.Contains(raw, ",") {
items := strings.Split(raw, ",")
for _, item := range items {
if strings.Contains(item, "-") {
min, err := strconv.Atoi(strings.Split(item, "-")[0])
if err != nil {
continue
}
max, err := strconv.Atoi(strings.Split(item, "-")[1])
if err != nil {
continue
}
for i := min; i <= max; i++ {
ports = append(ports, fmt.Sprintf("%v", i))
}
} else {
ports = append(ports, item)
}
}
} else {
if strings.Contains(raw, "-") {
min, err := strconv.Atoi(strings.Split(raw, "-")[0])
if err != nil {
return ports
}
max, err := strconv.Atoi(strings.Split(raw, "-")[1])
if err != nil {
return ports
}
for i := min; i <= max; i++ {
ports = append(ports, fmt.Sprintf("%v", i))
}
} else {
ports = append(ports, raw)
}
}
return ports
}