-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.go
63 lines (51 loc) · 1.71 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
package backupfs
import (
"path/filepath"
"strings"
)
// current OS filepath separator / or \
const separator = string(filepath.Separator)
// ByMostFilePathSeparators sorts the string by the number of file path separators
// the more nested this is, the further at the beginning of the string slice the path will be
type ByMostFilePathSeparators []string
func (a ByMostFilePathSeparators) Len() int { return len(a) }
func (a ByMostFilePathSeparators) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByMostFilePathSeparators) Less(i, j int) bool {
return !LessFilePathSeparators(a[i], a[j])
}
// ByLeastFilePathSeparators sorts the string by the number of file path separators
// the least nested the file path is, the further at the beginning it will be of the
// sorted string slice.
type ByLeastFilePathSeparators []string
func (a ByLeastFilePathSeparators) Len() int { return len(a) }
func (a ByLeastFilePathSeparators) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLeastFilePathSeparators) Less(i, j int) bool {
return LessFilePathSeparators(a[i], a[j])
}
// LessFilePathSeparators compares two file paths by the number of file path separators
// returns true if a has less file path separators than b
func LessFilePathSeparators(a, b string) bool {
aa := TrimVolume(a)
ab := TrimVolume(b)
ca := strings.Count(aa, separator)
cb := strings.Count(ab, separator)
/*
Edge case where the root path is compared to a file in the root path.
[0] = "/test/0/2"
[1] = "/test/0"
[2] = "/"
[3] = "/test"
*/
// root = smallest number of separators
if ca == 1 && aa == separator {
ca = -1
}
if cb == 1 && ab == separator {
cb = -1
}
if ca == cb {
// with volume
return a < b
}
return ca < cb
}