/
file_system.go
363 lines (310 loc) · 7.56 KB
/
file_system.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
package goutil
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/AspieSoft/go-regex-re2/v2"
"github.com/alphadose/haxmap"
"github.com/fsnotify/fsnotify"
)
type fileSystem struct {}
var FS *fileSystem = &fileSystem{}
// linux package installer
type LinuxPKG struct {
sudo bool
}
// JoinPath joins multiple file types with safety from backtracking
func (fs *fileSystem) JoinPath(path ...string) (string, error) {
resPath, err := filepath.Abs(string(path[0]))
if err != nil {
return "", err
}
for i := 1; i < len(path); i++ {
p := filepath.Join(resPath, string(path[i]))
if p == resPath || !strings.HasPrefix(p, resPath) {
return "", errors.New("path leaked outside of root")
}
resPath = p
}
return resPath, nil
}
var regDirEndSlash *regex.Regexp = regex.Comp(`[\\/][^\\/]*$`)
// GetFileFromParent checks if the parent (or sub parent) directory of a file contains a specific file or folder
//
// @root is the highest grandparent to check before quitting
//
// @start is the lowest level to start searching from (if a directory is passed, it will not be included in your search)
//
// @search is what file you want to search from
func (fs *fileSystem) GetFileFromParent(root string, start string, search string) (string, bool) {
dir := string(regDirEndSlash.RepStrLit([]byte(start), []byte{}))
if len(dir) == 0 || dir == root || !strings.HasPrefix(dir, root) {
return "", false
}
if dirList, err := os.ReadDir(string(dir)); err == nil {
for _, file := range dirList {
name := file.Name()
if name == search {
if path, err := fs.JoinPath(string(dir), name); err == nil {
return path, true
}
return "", false
}
}
}
return fs.GetFileFromParent(root, dir, search)
}
// A watcher instance for the `FS.FileWatcher` method
type FileWatcher struct {
fs *fileSystem
watcherList *haxmap.Map[string, *watcherObj]
// when a file changes
//
// @path: the file path the change happened to
//
// @op: the change operation
OnFileChange func(path string, op string)
// when a directory is added
//
// @path: the file path the change happened to
//
// @op: the change operation
//
// return false to prevent that directory from being watched
OnDirAdd func(path string, op string) (addWatcher bool)
// when a file or directory is removed
//
// @path: the file path the change happened to
//
// @op: the change operation
//
// return false to prevent that directory from no longer being watched
OnRemove func(path string, op string) (removeWatcher bool)
// every time something happenes
//
// @path: the file path the change happened to
//
// @op: the change operation
OnAny func(path string, op string)
}
type watcherObj struct {
watcher *fsnotify.Watcher
close *bool
}
func (fs *fileSystem) FileWatcher() *FileWatcher {
return &FileWatcher{fs: fs, watcherList: haxmap.New[string, *watcherObj]()}
}
// WatchDir watches the files in a directory and its subdirectories for changes
func (fw *FileWatcher) WatchDir(root string) error {
var err error
if root, err = filepath.Abs(root); err != nil {
return err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
runClose := false
fw.watcherList.Set(root, &watcherObj{watcher: watcher, close: &runClose})
go func() {
defer watcher.Close()
for {
if runClose {
break
}
if event, ok := <-watcher.Events; ok {
filePath := event.Name
stat, err := os.Stat(filePath)
if err != nil {
if fw.OnRemove == nil || fw.OnRemove(filePath, event.Op.String()){
watcher.Remove(filePath)
}
}else if stat.IsDir() {
if fw.OnDirAdd == nil || fw.OnDirAdd(filePath, event.Op.String()){
watcher.Add(filePath)
}
}else{
if fw.OnFileChange != nil {
fw.OnFileChange(filePath, event.Op.String())
}
}
if fw.OnAny != nil {
fw.OnAny(filePath, event.Op.String())
}
}
}
}()
err = watcher.Add(root)
if err != nil {
return err
}
fw.watchDirSub(watcher, root)
return nil
}
func (fw *FileWatcher) watchDirSub(watcher *fsnotify.Watcher, dir string){
files, err := os.ReadDir(dir)
if err != nil {
return
}
for _, file := range files {
if file.IsDir() {
if path, err := fw.fs.JoinPath(dir, file.Name()); err == nil {
watcher.Add(path)
fw.watchDirSub(watcher, path)
}
}
}
}
// CloseWatcher will close the watcher by the root name you used
//
// @root pass a file path for a specific watcher or "*" for all watchers that exist
func (fw *FileWatcher) CloseWatcher(root string) error {
if root == "" || root == "*" {
rList := []string{}
fw.watcherList.ForEach(func(r string, w *watcherObj) bool {
rList = append(rList, r)
*w.close = true
return true
})
fw.watcherList.Del(rList...)
}else{
var err error
if root, err = filepath.Abs(root); err != nil {
return err
}
if w, ok := fw.watcherList.Get(root); ok {
*w.close = true
fw.watcherList.Del(root)
}
}
return nil
}
// Wait for all Watchers to close
func (fw *FileWatcher) Wait(){
for fw.watcherList.Len() != 0 {
time.Sleep(100 * time.Nanosecond)
}
}
// InstallLinuxPkg attempts to install a linux package
//
// this method will also resolve the sudo command and ask for a user password if needed
//
// this method will not attempt to run an install, if it finds the package is already installed
func (linuxPKG *LinuxPKG) InstallLinuxPkg(pkg []string, man ...string){
if !linuxPKG.HasLinuxPkg(pkg) {
var pkgMan string
if len(man) != 0 {
pkgMan = man[0]
}else{
pkgMan = linuxPKG.GetLinuxInstaller([]string{`apt-get`, `apt`, `yum`})
}
var cmd *exec.Cmd
if linuxPKG.sudo {
cmd = exec.Command(`sudo`, append([]string{pkgMan, `install`, `-y`}, pkg...)...)
}else{
cmd = exec.Command(pkgMan, append([]string{`install`, `-y`}, pkg...)...)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return
}
go (func() {
out := bufio.NewReader(stdout)
for {
s, err := out.ReadString('\n')
if err == nil {
fmt.Println(s)
}
}
})()
stderr, err := cmd.StderrPipe()
if err != nil {
return
}
go (func() {
out := bufio.NewReader(stderr)
for {
s, err := out.ReadString('\n')
if err == nil {
fmt.Println(s)
}
}
})()
cmd.Run()
}
}
// HasLinuxPkg attempt to check if a linux package is installed
func (linuxPKG *LinuxPKG) HasLinuxPkg(pkg []string) bool {
for _, name := range pkg {
hasPackage := false
var cmd *exec.Cmd
if linuxPKG.sudo {
cmd = exec.Command(`sudo`, `dpkg`, `-s`, name)
}else{
cmd = exec.Command(`dpkg`, `-s`, name)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return true
}
go (func() {
out := bufio.NewReader(stdout)
for {
_, err := out.ReadString('\n')
if err == nil {
hasPackage = true
}
}
})()
for i := 0; i < 3; i++ {
cmd.Run()
if hasPackage {
break
}
}
if !hasPackage {
return false
}
}
return true
}
// GetLinuxInstaller attempt to find out what package manager a linux distro is using or has available
func (linuxPKG *LinuxPKG) GetLinuxInstaller(man []string) string {
hasInstaller := ""
for _, m := range man {
var cmd *exec.Cmd
if linuxPKG.sudo {
cmd = exec.Command(`sudo`, `dpkg`, `-s`, m)
}else{
cmd = exec.Command(`dpkg`, `-s`, m)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
continue
}
go (func() {
out := bufio.NewReader(stdout)
for {
_, err := out.Peek(1)
if err == nil {
hasInstaller = m
}
}
})()
for i := 0; i < 3; i++ {
cmd.Run()
if hasInstaller != "" {
break
}
}
if hasInstaller != "" {
break
}
}
return hasInstaller
}