-
Notifications
You must be signed in to change notification settings - Fork 4
/
read.go
92 lines (72 loc) · 1.82 KB
/
read.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
package read
import (
"os"
"go.k6.io/k6/js/modules"
)
func init() {
modules.Register("k6/x/read", new(READ))
}
// READ is the k6 extension
type READ struct{}
// Item is the extension file system item representation (file or directory).
type Item interface {
GetPath() string
GetContent() any
}
// Directory is the extension directory representation
type Directory struct {
Item
Path string
Content []Item
}
func (d *Directory) GetPath() string {
return d.Path
}
func (d *Directory) GetContent() any {
return d.Content
}
// File is the extension file representation
type File struct {
Item
Path string
Content string
Binary []byte
}
func (f *File) GetPath() string {
return f.Path
}
func (f *File) GetContent() any {
return f.Content
}
func (r *READ) ReadDirectory(path string) (Directory, error) {
directoryEntries, readError := os.ReadDir(path)
if readError != nil {
return Directory{}, readError
} else {
directory := Directory{Path: path, Content: make([]Item, len(directoryEntries))}
for i := 0; i < len(directoryEntries); i++ {
if directoryEntries[i].IsDir() {
newDirectory, _ := r.ReadDirectory(path + "/" + directoryEntries[i].Name())
directory.Content[i] = &newDirectory
} else {
newFile, _ := r.ReadFile(path + "/" + directoryEntries[i].Name())
directory.Content[i] = &newFile
}
}
return directory, readError
}
}
func (*READ) ReadFile(path string) (File, error) {
fileContent, readError := os.ReadFile(path)
if readError != nil {
return File{}, readError
}
return File{Path: path, Content: string(fileContent)}, nil
}
func (*READ) ReadBinaryFile(path string) (File, error) {
fileContent, readError := os.ReadFile(path)
if readError != nil {
return File{}, readError
}
return File{Path: path, Binary: fileContent}, nil
}