-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdirectory.go
93 lines (78 loc) · 2.02 KB
/
directory.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
package scrubber
import (
"os"
)
// directory holds the cleanup information for a single path in the filesystem.
type directory struct {
Name string
Path string
Include []string
Exclude []string
Strategies []StrategyConfig `toml:"strategy"`
KeepLatest int
}
// WithPath returns a copy of the struct with the Path field set to dir.
func (d directory) WithPath(dir string) directory {
return directory{
Name: d.Name,
Path: dir,
Include: d.Include,
Exclude: d.Exclude,
Strategies: d.Strategies,
}
}
// directoryScanner is used to scan a directory for files.
type directoryScanner struct {
dir *directory
fs Filesystem
}
// newDirectoryScanner returns a pointer to a directoryScanner.
func newDirectoryScanner(dir *directory, fs Filesystem) *directoryScanner {
return &directoryScanner{
dir,
fs,
}
}
// getFiles returns all files in the cleanup directory.
func (s directoryScanner) getFiles() ([]os.FileInfo, error) {
return s.fs.ListFiles(s.dir.Path)
}
// filterFiles applies the include and exclude rules to all files in the cleanup directory.
func (s directoryScanner) filterFiles(files []os.FileInfo) []os.FileInfo {
var filtered []os.FileInfo
for _, file := range files {
if !file.Mode().IsRegular() {
continue
}
fileExt := s.fs.Ext(file)
var include bool
if s.dir.Include != nil {
include = includesExtension(s.dir.Include, fileExt)
} else {
include = !includesExtension(s.dir.Exclude, fileExt)
}
if include {
filtered = append(filtered, file)
}
}
return filtered
}
// includesExtension checks if a certain extension is an element of extensions.
func includesExtension(extensions []string, fileExt string) bool {
for _, ext := range extensions {
if "."+ext == fileExt {
return true
}
}
return false
}
// ApplyKeepLatest applies the keep latest rule to a slice of files.
func ApplyKeepLatest(files []os.FileInfo, latest int) []os.FileInfo {
if latest < 1 {
return files
}
if len(files) > latest {
return files[latest:]
}
return files
}