-
Notifications
You must be signed in to change notification settings - Fork 30
/
folderutil.go
257 lines (230 loc) · 6.26 KB
/
folderutil.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
package folderutil
import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/pkg/errors"
fileutil "github.com/projectdiscovery/utils/file"
mapsutil "github.com/projectdiscovery/utils/maps"
)
var (
// Separator evaluated at runtime
Separator = string(os.PathSeparator)
// Remove source directory after successful sync
RemoveSourceDirAfterSync = true
// writeablePathCache is a cache of writeable paths
writeablePathCache = mapsutil.SyncLockMap[string, struct{}]{
Map: make(map[string]struct{}),
}
)
const (
UnixPathSeparator = "/"
WindowsPathSeparator = "\\"
)
// GetFiles within a folder
func GetFiles(root string) ([]string, error) {
var matches []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
matches = append(matches, path)
return nil
})
if err != nil {
return nil, err
}
return matches, nil
}
// PathInfo about a folder
type PathInfo struct {
IsAbsolute bool
RootPath string
Parts []string
PartsWithSeparator []string
}
// NewPathInfo returns info about a given path
func NewPathInfo(path string) (PathInfo, error) {
var pathInfo PathInfo
path = filepath.Clean(path)
pathInfo.RootPath = filepath.VolumeName(path)
if filepath.IsAbs(path) {
if IsUnixOS() {
if pathInfo.RootPath == "" {
pathInfo.IsAbsolute = true
pathInfo.RootPath = UnixPathSeparator
}
} else if IsWindowsOS() {
pathInfo.IsAbsolute = true
pathInfo.RootPath = pathInfo.RootPath + WindowsPathSeparator
}
}
pathInfo.Parts = agnosticSplit(path)
for i, pathItem := range pathInfo.Parts {
if i == 0 && pathInfo.IsAbsolute {
if IsUnixOS() {
pathInfo.PartsWithSeparator = append(pathInfo.PartsWithSeparator, pathInfo.RootPath)
}
} else if len(pathInfo.PartsWithSeparator) > 0 && pathInfo.PartsWithSeparator[len(pathInfo.PartsWithSeparator)-1] != Separator {
pathInfo.PartsWithSeparator = append(pathInfo.PartsWithSeparator, Separator)
}
pathInfo.PartsWithSeparator = append(pathInfo.PartsWithSeparator, pathItem)
}
return pathInfo, nil
}
// Returns all possible combination of the various levels of the path parts
func (pathInfo PathInfo) Paths() ([]string, error) {
var combos []string
for i := 0; i <= len(pathInfo.Parts); i++ {
var computedPath string
if pathInfo.IsAbsolute && pathInfo.RootPath != "" {
// on windows we need to skip the volume, already computed in rootpath
if IsUnixOS() {
computedPath = pathInfo.RootPath + filepath.Join(pathInfo.Parts[:i]...)
} else if IsWindowsOS() && i > 0 {
skipItems := 0
if len(pathInfo.Parts) > 0 {
skipItems = 1
}
computedPath = pathInfo.RootPath + filepath.Join(pathInfo.Parts[skipItems:i]...)
}
} else {
computedPath = filepath.Join(pathInfo.Parts[:i]...)
}
combos = append(combos, filepath.Clean(computedPath))
}
return combos, nil
}
// MeshWith combine all values from Path with another provided path
func (pathInfo PathInfo) MeshWith(anotherPath string) ([]string, error) {
allPaths, err := pathInfo.Paths()
if err != nil {
return nil, err
}
var combos []string
for _, basePath := range allPaths {
combinedPath := filepath.Join(basePath, anotherPath)
combos = append(combos, filepath.Clean(combinedPath))
}
return combos, nil
}
func IsUnixOS() bool {
switch runtime.GOOS {
case "android", "darwin", "freebsd", "ios", "linux", "netbsd", "openbsd", "solaris":
return true
default:
return false
}
}
func IsWindowsOS() bool {
return runtime.GOOS == "windows"
}
func agnosticSplit(path string) (parts []string) {
// split with each known separators
for _, part := range strings.Split(path, UnixPathSeparator) {
for _, subPart := range strings.Split(part, WindowsPathSeparator) {
if part != "" {
parts = append(parts, subPart)
}
}
}
return
}
// IsWritable checks if a path is writable by attempting to create a temporary file.
// It caches writable paths to avoid unnecessary file operations.
func IsWritable(path string) bool {
if _, ok := writeablePathCache.Get(path); ok {
return true
}
if !fileutil.FolderExists(path) {
return false
}
tmpfile, err := os.CreateTemp(path, "test")
if err != nil {
return false
}
_ = tmpfile.Close()
_ = os.Remove(tmpfile.Name())
_ = writeablePathCache.Set(path, struct{}{})
return true
}
// SyncDirectory sync all files and non-empty directories from source to destination folder
// optionally removes source directory and removes source
func SyncDirectory(source, destination string) error {
// trim trailing slash to avoid slash related issues
source = strings.TrimSuffix(source, Separator)
destination = strings.TrimSuffix(destination, Separator)
if !fileutil.FolderExists(source) {
return errors.New("source directory doesn't exist")
}
if fileutil.FolderExists(destination) {
sourceStat, err := os.Stat(source)
if err != nil {
return err
}
destinationStat, err := os.Stat(destination)
if err != nil {
return err
}
if os.SameFile(sourceStat, destinationStat) {
return errors.New("source and destination cannot be the same")
}
}
entries, err := os.ReadDir(source)
if err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(source, entry.Name())
destPath := filepath.Join(destination, entry.Name())
if entry.IsDir() {
subentries, err := os.ReadDir(sourcePath)
if err != nil {
return err
}
if len(subentries) > 0 {
err = os.MkdirAll(destPath, os.ModePerm)
if err != nil {
return err
}
err = SyncDirectory(sourcePath, destPath)
if err != nil {
return err
}
}
} else {
err = os.Rename(sourcePath, destPath)
if err != nil {
return err
}
}
}
if RemoveSourceDirAfterSync {
err = os.RemoveAll(source)
if err != nil {
return err
}
}
return nil
}
// DedupeLinesInFiles deduplicates lines in all files in a directory
// The function can be memory intensive for directories with large files.
func DedupeLinesInFiles(dir string) error {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return fileutil.DedupeLines(path)
}
return nil
})
if err != nil {
return errors.Wrapf(err, "error processing directory %s", dir)
}
return nil
}