-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
117 lines (96 loc) · 2.08 KB
/
file.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
package cidsdk
import (
"os"
"path/filepath"
"strings"
cp "github.com/otiai10/copy"
)
type FileRequest struct {
Directory string `json:"dir"`
Extensions []string `json:"ext"`
}
type File struct {
Path string `json:"path"`
Directory string `json:"dir"`
Name string `json:"name"`
NameShort string `json:"name_short"`
Extension string `json:"ext"`
}
func NewFile(path string) File {
split := strings.SplitN(filepath.Base(path), ".", 2)
fileName := split[0]
fileExt := ""
if len(split) > 1 && split[1] != "" {
fileExt = "." + split[1]
}
return File{
Path: path,
Directory: filepath.Dir(path),
Name: filepath.Base(path),
NameShort: fileName,
Extension: fileExt,
}
}
// FileRead command
func (sdk SDK) FileRead(file string) (string, error) {
data, err := os.ReadFile(file)
if err != nil {
return "", err
}
return string(data), nil
}
// FileList command
func (sdk SDK) FileList(req FileRequest) (files []File, err error) {
err = filepath.Walk(req.Directory, func(path string, info os.FileInfo, err error) error {
if info != nil && !info.IsDir() {
if len(req.Extensions) > 0 {
for _, ext := range req.Extensions {
if strings.HasSuffix(path, ext) {
files = append(files, NewFile(path))
break
}
}
} else {
files = append(files, NewFile(path))
}
}
return nil
})
return
}
// FileRename command
func (sdk SDK) FileRename(old string, new string) error {
err := os.Rename(old, new)
if err != nil {
return err
}
return nil
}
// FileCopy command
func (sdk SDK) FileCopy(old string, new string) error {
err := cp.Copy(old, new)
return err
}
// FileRemove command
func (sdk SDK) FileRemove(file string) error {
err := os.Remove(file)
if err != nil {
return err
}
return nil
}
// FileWrite command
func (sdk SDK) FileWrite(file string, content []byte) error {
err := os.WriteFile(file, content, os.ModePerm)
if err != nil {
return err
}
return nil
}
// FileExists command
func (sdk SDK) FileExists(file string) bool {
if _, err := os.Stat(file); err == nil {
return true
}
return false
}