-
Notifications
You must be signed in to change notification settings - Fork 0
/
folder.go
124 lines (104 loc) · 2.38 KB
/
folder.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
package nginx
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
// Namespace imports
. "github.com/djthorpe/go-errors"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
// Folder tracks files within a folder
type Folder struct {
path string
recursive bool
}
///////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
func NewFolder(path string, recursive bool) (*Folder, error) {
f := new(Folder)
// Check to make sure path is valid
if info, err := os.Stat(path); os.IsNotExist(err) {
return nil, ErrNotFound.With(path)
} else if err != nil {
return nil, err
} else if !info.IsDir() {
return nil, ErrBadParameter.With(path)
} else {
f.path = path
f.recursive = recursive
}
// Return success
return f, nil
}
///////////////////////////////////////////////////////////////////////////////
// STRINFIGY
func (f *Folder) String() string {
str := "<nginx-folder"
str += fmt.Sprintf(" path=%q", f.path)
if f.recursive {
str += " recursive"
}
return str + ">"
}
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
func (f *Folder) RelPath(root string) string {
if root == "" {
return f.path
} else if rel, err := filepath.Rel(root, f.path); err != nil {
return f.path
} else {
return rel
}
}
func (f *Folder) Enumerate() ([]*File, error) {
var result []*File
if err := filepath.WalkDir(f.path, func(path string, d fs.DirEntry, err error) error {
// Skip errors
if err != nil {
return err
}
// Ignore hidden files
if strings.HasPrefix(d.Name(), ".") && f.path != path {
if d.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
// Recurse into directories
if d.IsDir() && f.path != path {
if f.recursive {
return nil
} else {
return filepath.SkipDir
}
}
// Only enumerate regular files
if info, err := d.Info(); err != nil {
return nil
} else if validFileMode(info.Mode()) {
result = append(result, NewFile(path, info))
}
// Return success
return nil
}); err != nil {
return nil, err
} else {
return result, nil
}
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
func validFileMode(mode fs.FileMode) bool {
if mode.IsRegular() {
return true
}
if mode.Type() == fs.ModeSymlink {
return true
}
return false
}