-
Notifications
You must be signed in to change notification settings - Fork 37
/
path_collector.go
127 lines (112 loc) · 2.59 KB
/
path_collector.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
package yamlfmt
import (
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/bmatcuk/doublestar/v4"
"github.com/google/yamlfmt/internal/collections"
)
type PathCollector interface {
CollectPaths() ([]string, error)
}
type FilepathCollector struct {
Include []string
Exclude []string
Extensions []string
}
func (c *FilepathCollector) CollectPaths() ([]string, error) {
pathsFound := []string{}
for _, inclPath := range c.Include {
info, err := os.Stat(inclPath)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
continue
}
if !info.IsDir() {
pathsFound = append(pathsFound, inclPath)
continue
}
paths, err := c.walkDirectoryForYaml(inclPath)
if err != nil {
return nil, err
}
pathsFound = append(pathsFound, paths...)
}
pathsFoundSet := collections.SliceToSet(pathsFound)
pathsToFormat := collections.SliceToSet(pathsFound)
for _, exclPath := range c.Exclude {
info, err := os.Stat(exclPath)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
continue
}
if info.IsDir() {
for foundPath := range pathsFoundSet {
if strings.HasPrefix(foundPath, exclPath) {
pathsToFormat.Remove(foundPath)
}
}
} else {
pathsToFormat.Remove(exclPath)
}
}
return pathsToFormat.ToSlice(), nil
}
func (c *FilepathCollector) walkDirectoryForYaml(dir string) ([]string, error) {
paths := []string{}
err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
if info.IsDir() {
return nil
}
extension := ""
if strings.Contains(info.Name(), ".") {
nameParts := strings.Split(info.Name(), ".")
extension = nameParts[len(nameParts)-1]
}
if collections.SliceContains(c.Extensions, extension) {
paths = append(paths, path)
}
return nil
})
return paths, err
}
type DoublestarCollector struct {
Include []string
Exclude []string
}
func (c *DoublestarCollector) CollectPaths() ([]string, error) {
includedPaths := []string{}
for _, pattern := range c.Include {
globMatches, err := doublestar.FilepathGlob(pattern)
if err != nil {
return nil, err
}
includedPaths = append(includedPaths, globMatches...)
}
pathsToFormatSet := collections.Set[string]{}
for _, path := range includedPaths {
if len(c.Exclude) == 0 {
pathsToFormatSet.Add(path)
continue
}
excluded := false
for _, pattern := range c.Exclude {
match, err := doublestar.PathMatch(filepath.Clean(pattern), path)
if err != nil {
return nil, err
}
if match {
excluded = true
}
}
if !excluded {
pathsToFormatSet.Add(path)
}
}
return pathsToFormatSet.ToSlice(), nil
}