-
Notifications
You must be signed in to change notification settings - Fork 2
/
filepath.go
370 lines (307 loc) · 8.64 KB
/
filepath.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/essentials source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package ess
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// Excludes is handly filepath match manipulation
type Excludes []string
// Validate helps to evalute the pattern are valid
// `Match` method is from error and focus on match
func (e *Excludes) Validate() error {
for _, pattern := range *e {
if _, err := filepath.Match(pattern, "abc/b/c"); err != nil {
return fmt.Errorf("unable to evalute pattern: %v", pattern)
}
}
return nil
}
// Match evalutes given file with available patterns returns true if matches
// otherwise false. `Match` internally uses the `filepath.Match`
//
// Note: `Match` ignore pattern errors, use `Validate` method to ensure
// you have correct exclude patterns
func (e *Excludes) Match(file string) bool {
for _, pattern := range *e {
if match, _ := filepath.Match(pattern, file); match {
return match
}
}
return false
}
// IsFileExists return true is file or directory is exists, otherwise returns
// false. It also take cares of symlink path as well
func IsFileExists(filename string) bool {
_, err := os.Lstat(filename)
return err == nil
}
// IsDirEmpty returns true if the given directory is empty also returns true if
// directory not exists. Otherwise returns false
func IsDirEmpty(path string) bool {
if !IsFileExists(path) {
// directory not exists
return true
}
dir, _ := os.Open(path)
defer CloseQuietly(dir)
results, _ := dir.Readdir(1)
return len(results) == 0
}
// IsDir returns true if the given `path` is directory otherwise returns false.
// Also returns false if path is not exists
func IsDir(path string) bool {
info, err := os.Lstat(path)
return err == nil && info.IsDir()
}
// ApplyFileMode applies the given file mode to the target{file|directory}
func ApplyFileMode(target string, mode os.FileMode) error {
err := os.Chmod(target, mode)
if err != nil {
return fmt.Errorf("unable to apply mode: %v, to given file or directory: %v", mode, target)
}
return nil
}
// LineCnt counts no. of lines on file
func LineCnt(fileName string) int {
f, err := os.Open(fileName)
if err != nil {
return 0
}
defer CloseQuietly(f)
return LineCntr(f)
}
// LineCntr counts no. of lines for given reader
func LineCntr(r io.Reader) int {
buf := make([]byte, 8196)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
if err != nil && err != io.EOF {
return count
}
count += bytes.Count(buf[:c], lineSep)
if err == io.EOF {
break
}
}
return count
}
// Walk method extends filepath.Walk to also follows symlinks.
// Always returns the path of the file or directory also path
// is inline to name of symlink
func Walk(srcDir string, walkFn filepath.WalkFunc) error {
return doWalk(srcDir, srcDir, walkFn)
}
func doWalk(fname string, linkName string, walkFn filepath.WalkFunc) error {
fsWalkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
var name string
name, err = filepath.Rel(fname, path)
if err != nil {
return err
}
path = filepath.Join(linkName, name)
if err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {
var symlinkPath string
symlinkPath, err = filepath.EvalSymlinks(path)
if err != nil {
return err
}
info, err = os.Lstat(symlinkPath)
if err != nil {
return walkFn(path, info, err)
}
if info.IsDir() {
return doWalk(symlinkPath, path, walkFn)
}
}
return walkFn(path, info, err)
}
return filepath.Walk(fname, fsWalkFn)
}
// CopyFile copies the given source file into destination
func CopyFile(dest, src string) (int64, error) {
if !IsFileExists(src) {
return 0, fmt.Errorf("source file does not exists: %v", src)
}
baseName := filepath.Base(src)
if !strings.HasSuffix(dest, baseName) {
dest = filepath.Join(dest, baseName)
}
if IsFileExists(dest) {
return 0, fmt.Errorf("destination file already exists: %v", dest)
}
destFile, err := os.Create(dest)
if err != nil {
return 0, fmt.Errorf("unable to create dest file: %v", dest)
}
defer CloseQuietly(destFile)
srcFile, err := os.Open(src)
if err != nil {
return 0, fmt.Errorf("unable to open source file: %v", src)
}
defer CloseQuietly(srcFile)
copiedBytes, err := io.Copy(destFile, srcFile)
if err != nil {
return 0, fmt.Errorf("unable to copy file from %v to %v (%v)",
src, dest, err)
}
return copiedBytes, nil
}
// CopyDir copies entire directory, sub directories and files into destination
// and it excludes give file matches
func CopyDir(dest, src string, excludes Excludes) error {
if !IsFileExists(src) {
return fmt.Errorf("source dir does not exists: %v", src)
}
src = filepath.Clean(src)
srcInfo, _ := os.Lstat(src)
if !srcInfo.IsDir() {
return fmt.Errorf("source is not directory: %v", src)
}
baseName := filepath.Base(src)
if !strings.HasSuffix(dest, baseName) {
dest = filepath.Join(dest, baseName)
}
if IsFileExists(dest) {
return fmt.Errorf("destination dir already exists: %v", dest)
}
if err := excludes.Validate(); err != nil {
return err
}
return Walk(src, func(srcPath string, info os.FileInfo, err error) error {
if excludes.Match(filepath.Base(srcPath)) {
if info.IsDir() {
// excluding directory
return filepath.SkipDir
}
// excluding file
return nil
}
relativeSrcPath := strings.TrimLeft(srcPath[len(src):], string(filepath.Separator))
destPath := filepath.Join(dest, relativeSrcPath)
if info.IsDir() {
// directory permissions is not preserved from source
return MkDirAll(destPath, 0755)
}
// copy source into destination
if _, err = CopyFile(destPath, srcPath); err != nil {
return err
}
// Apply source permision into target as well
// so file permissions are preserved
return ApplyFileMode(destPath, info.Mode())
})
}
// DeleteFiles method deletes give files or directories. ensure your supplying
// appropriate paths.
func DeleteFiles(files ...string) (errs []error) {
for _, f := range files {
if !IsFileExists(f) {
errs = append(errs, fmt.Errorf("path does not exists: %s", f))
continue
}
var err error
if IsDir(f) {
err = os.RemoveAll(f)
} else {
err = os.Remove(f)
}
if err != nil {
errs = append(errs, err)
}
}
return
}
// DirsPath method returns all directories absolute path from given base path recursively.
func DirsPath(basePath string, recursive bool) (pdirs []string, err error) {
return DirsPathExcludes(basePath, recursive, Excludes{})
}
// DirsPathExcludes method returns all directories absolute path from given base path recursively
// excluding the excludes list.
func DirsPathExcludes(basePath string, recursive bool, excludes Excludes) (pdirs []string, err error) {
if err = excludes.Validate(); err != nil {
return
}
if recursive {
err = Walk(basePath, func(srcPath string, info os.FileInfo, err error) error {
if info.IsDir() && excludes.Match(filepath.Base(srcPath)) {
// excluding directory
return filepath.SkipDir
}
if info.IsDir() {
pdirs = append(pdirs, srcPath)
}
return nil
})
return
}
var list []os.FileInfo
list, err = ioutil.ReadDir(basePath)
if err != nil {
return
}
for _, v := range list {
if v.IsDir() && !excludes.Match(v.Name()) {
pdirs = append(pdirs, filepath.Join(basePath, v.Name()))
}
}
return
}
// FilesPath method returns all files absolute path from given base path recursively.
func FilesPath(basePath string, recursive bool) (files []string, err error) {
return FilesPathExcludes(basePath, recursive, Excludes{})
}
// FilesPathExcludes method returns all files absolute path from given base path recursively
// excluding the excludes list.
func FilesPathExcludes(basePath string, recursive bool, excludes Excludes) (files []string, err error) {
if err = excludes.Validate(); err != nil {
return
}
if recursive {
err = Walk(basePath, func(srcPath string, info os.FileInfo, err error) error {
if !info.IsDir() && excludes.Match(filepath.Base(srcPath)) {
// excluding file
return nil
}
if !info.IsDir() {
files = append(files, srcPath)
}
return nil
})
return
}
var list []os.FileInfo
list, err = ioutil.ReadDir(basePath)
if err != nil {
return
}
for _, v := range list {
if !v.IsDir() && !excludes.Match(v.Name()) {
files = append(files, filepath.Join(basePath, v.Name()))
}
}
return
}
// StripExt method returns name of the file without extension.
// E.g.: index.html => index
func StripExt(name string) string {
if IsStrEmpty(name) {
return name
}
idx := strings.LastIndexByte(name, '.')
if idx > 0 {
return name[:idx]
}
return name
}