-
Notifications
You must be signed in to change notification settings - Fork 13
/
laster.go
44 lines (40 loc) · 979 Bytes
/
laster.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
package metha
import (
"io/ioutil"
"os"
"sort"
)
// Laster extracts some maximum value as string.
type Laster interface {
Last() (string, error)
}
// DirLaster extract the maximum value from the files of a directory. The values
// are extracted per file via TransformFunc, which gets a filename and returns a
// token. The tokens are sorted and the lexikographically largest element is
// returned.
type DirLaster struct {
Dir string
DefaultValue string
ExtractorFunc func(os.FileInfo) string
}
// Last extracts the maximum value from a directory, given an extractor function.
func (l DirLaster) Last() (string, error) {
files, err := ioutil.ReadDir(l.Dir)
if err != nil {
return "", err
}
var (
values []string
v string
)
for _, fi := range files {
if v = l.ExtractorFunc(fi); v != "" {
values = append(values, v)
}
}
sort.Strings(values)
if len(values) > 0 {
return values[len(values)-1], nil
}
return l.DefaultValue, nil
}