-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathsort.go
101 lines (85 loc) · 1.78 KB
/
sort.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
package notes
import (
"github.com/pkg/errors"
"os"
"sort"
"strings"
"time"
)
type byCreated []*Note
func (a byCreated) Len() int {
return len(a)
}
func (a byCreated) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byCreated) Less(i, j int) bool {
return a[i].Created.After(a[j].Created)
}
func sortByCreated(n []*Note) {
sort.Sort(byCreated(n))
}
type byFilename []*Note
func (a byFilename) Len() int {
return len(a)
}
func (a byFilename) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byFilename) Less(i, j int) bool {
return strings.Compare(a[i].File, a[j].File) < 0
}
func sortByFilename(n []*Note) {
sort.Sort(byFilename(n))
}
type byCategory []*Note
func (a byCategory) Len() int {
return len(a)
}
func (a byCategory) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byCategory) Less(i, j int) bool {
l, r := a[i], a[j]
cmp := strings.Compare(l.Category, r.Category)
if cmp != 0 {
return cmp < 0
}
return strings.Compare(l.File, r.File) < 0
}
func sortByCategory(n []*Note) {
sort.Sort(byCategory(n))
}
type byModified struct {
a []*Note
t map[*Note]time.Time
}
func (by *byModified) Len() int {
return len(by.a)
}
func (by *byModified) Swap(i, j int) {
a := by.a
a[i], a[j] = a[j], a[i]
}
func (by *byModified) Less(i, j int) bool {
a := by.a
l, r := by.t[a[i]], by.t[a[j]]
return l.After(r)
}
// sortByModified sorts given notes by modified time. When an error occurs, the order of given notes
// is undefined. The latest is the first.
func sortByModified(notes []*Note) error {
by := &byModified{
a: notes,
t: make(map[*Note]time.Time, len(notes)),
}
for _, n := range notes {
s, err := os.Stat(n.FilePath())
if err != nil {
return errors.Wrap(err, "Cannot sort by modified time")
}
by.t[n] = s.ModTime()
}
sort.Sort(by)
return nil
}