forked from flarco/g
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilesys.go
More file actions
81 lines (73 loc) · 2.17 KB
/
filesys.go
File metadata and controls
81 lines (73 loc) · 2.17 KB
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
package g
import (
"os"
"path"
"path/filepath"
"strings"
)
// FileItem represents a file or a directory
type FileItem struct {
Name string `json:"name,omitempty"`
RelPath string `json:"rel_path,omitempty"` // relative path
FullPath string `json:"full_path,omitempty"`
ParentPath string `json:"parent_path,omitempty"`
IsDir bool `json:"is_dir,omitempty"`
ModTs int64 `json:"mod_ts,omitempty"`
Size int64 `json:"size,omitempty"`
}
// ListDir lists the file in given directory path recursively
func ListDir(dirPath string) (files []FileItem, err error) {
entries, err := os.ReadDir(dirPath)
if err != nil {
err = Error(err, "unable to read directory %s", dirPath)
return
}
for _, entry := range entries {
info, _ := entry.Info()
fullpath := filepath.Clean(path.Join(dirPath, entry.Name()))
file := FileItem{
Name: entry.Name(),
RelPath: entry.Name(),
FullPath: fullpath,
ParentPath: filepath.Dir(fullpath),
IsDir: entry.IsDir(),
ModTs: info.ModTime().Unix(),
Size: info.Size(),
}
file.RelPath = strings.TrimPrefix(file.RelPath, "./")
file.RelPath = strings.TrimPrefix(file.RelPath, "/")
file.RelPath = strings.TrimPrefix(file.RelPath, `\`)
files = append(files, file)
}
return
}
// ListDirRecursive lists the file in given directory path recursively
func ListDirRecursive(dirPath string) (files []FileItem, err error) {
walkFunc := func(subPath string, info os.FileInfo, err error) error {
if err != nil {
return err
} else if subPath == dirPath {
return nil
}
subPath = filepath.Clean(subPath)
file := FileItem{
Name: info.Name(),
RelPath: strings.TrimPrefix(subPath, dirPath),
FullPath: subPath,
ParentPath: filepath.Dir(subPath),
IsDir: info.IsDir(),
ModTs: info.ModTime().Unix(),
Size: info.Size(),
}
file.RelPath = strings.TrimPrefix(file.RelPath, "./")
file.RelPath = strings.TrimPrefix(file.RelPath, "/")
file.RelPath = strings.TrimPrefix(file.RelPath, `\`)
files = append(files, file)
return nil
}
err = filepath.Walk(dirPath, walkFunc)
if err != nil {
err = Error(err, "Error listing "+dirPath)
}
return
}