-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir.go
63 lines (54 loc) · 1.25 KB
/
dir.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
// Package dir contains a function to return the most recently modified file
// found at a Glob pattern and a supporting sort utility.
package dir
import (
"log"
"os"
"path/filepath"
"sort"
"time"
)
// LastModifiedFile returns a string path to the most recently modified file
// at a glob pattern.
func LastModifiedFile(pattern string) string {
filenames, err := filepath.Glob(pattern)
if err != nil {
log.Fatal(err)
}
var files []file
for _, f := range filenames {
file := file{path: f, mtime: getModTime(f)}
files = append(files, file)
}
sort.Sort(byTime(files))
if len(files) > 0 {
return files[len(files)-1].path
} else {
return ""
}
}
func getModTime(path string) time.Time {
fileInfo, err := os.Stat(path)
if err != nil {
log.Fatal(err)
}
return fileInfo.ModTime()
}
type file struct {
path string
mtime time.Time
}
// type byTime and its functions Len, Less and Swap are supporting
// implementations to allow for sorting a slice of files by their
// modification time.
// https://gobyexample.com/sorting-by-functions
type byTime []file
func (bt byTime) Len() int {
return len(bt)
}
func (bt byTime) Less(i, j int) bool {
return bt[i].mtime.Before(bt[j].mtime)
}
func (bt byTime) Swap(i, j int) {
bt[i], bt[j] = bt[j], bt[i]
}