-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile_sorter.go
60 lines (48 loc) · 1.17 KB
/
file_sorter.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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
)
type File struct {
Path string
os.FileInfo
}
type Files []*File
type ByName struct{ Files }
type ByMtime struct{ Files }
func (a Files) Len() int { return len(a) }
func (a Files) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByName) Less(i, j int) bool { return a.Files[i].Path < a.Files[j].Path }
func (a ByMtime) Less(i, j int) bool {
return a.Files[i].ModTime().Before(a.Files[j].ModTime())
}
func (f File) String() string {
return fmt.Sprintf("{%s: %v %d}", f.Path, f.ModTime(), f.Size())
}
/*
* Sorts files by descending mtime with an optional regex filtering.
*/
func fileSorter(path string, filter ...string) Files {
var files Files
err := filepath.Walk(path,
func(path string, info os.FileInfo, err error) error {
if err == nil && info.Mode().IsRegular() {
matched := true
// filter by regex
if len(filter) > 0 {
matched, _ = regexp.MatchString(filter[0], filepath.Base(path))
}
if matched {
files = append(files, &File{Path: path, FileInfo: info})
}
}
return nil
},
)
checkError(err)
sort.Sort(sort.Reverse(ByMtime{files}))
return files
}