| 1 |
package sort |
| 2 |
|
| 3 |
import ( |
| 4 |
"cmp" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"slices" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"git.sr.ht/~rjarry/aerc/models" |
| 11 |
"git.sr.ht/~rjarry/aerc/worker/types" |
| 12 |
) |
| 13 |
|
| 14 |
func GetSortCriteria(args []string) ([]*types.SortCriterion, error) { |
| 15 |
var sortCriteria []*types.SortCriterion |
| 16 |
reverse := false |
| 17 |
for _, arg := range args { |
| 18 |
if arg == "-r" { |
| 19 |
reverse = true |
| 20 |
continue |
| 21 |
} |
| 22 |
field, err := parseSortField(arg) |
| 23 |
if err != nil { |
| 24 |
return nil, err |
| 25 |
} |
| 26 |
sortCriteria = append(sortCriteria, &types.SortCriterion{ |
| 27 |
Field: field, |
| 28 |
Reverse: reverse, |
| 29 |
}) |
| 30 |
reverse = false |
| 31 |
} |
| 32 |
if reverse { |
| 33 |
return nil, errors.New("Expected argument to reverse") |
| 34 |
} |
| 35 |
return sortCriteria, nil |
| 36 |
} |
| 37 |
|
| 38 |
func parseSortField(arg string) (types.SortField, error) { |
| 39 |
switch strings.ToLower(arg) { |
| 40 |
case "arrival": |
| 41 |
return types.SortArrival, nil |
| 42 |
case "cc": |
| 43 |
return types.SortCc, nil |
| 44 |
case "date": |
| 45 |
return types.SortDate, nil |
| 46 |
case "from": |
| 47 |
return types.SortFrom, nil |
| 48 |
case "read": |
| 49 |
return types.SortRead, nil |
| 50 |
case "size": |
| 51 |
return types.SortSize, nil |
| 52 |
case "subject": |
| 53 |
return types.SortSubject, nil |
| 54 |
case "to": |
| 55 |
return types.SortTo, nil |
| 56 |
case "flagged": |
| 57 |
return types.SortFlagged, nil |
| 58 |
default: |
| 59 |
return types.SortArrival, fmt.Errorf("%v is not a valid sort criterion", arg) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
// Sorts toSort by sortBy so that toSort becomes a permutation following the |
| 64 |
// order of sortBy. |
| 65 |
// toSort should be a subset of sortBy |
| 66 |
func SortBy(toSort []models.UID, sortBy []models.UID) { |
| 67 |
// build a map from sortBy |
| 68 |
uidMap := make(map[models.UID]int) |
| 69 |
for i, uid := range sortBy { |
| 70 |
uidMap[uid] = i |
| 71 |
} |
| 72 |
// sortslice of toSort with less function of indexing the map sortBy |
| 73 |
slices.SortFunc(toSort, func(a, b models.UID) int { |
| 74 |
return cmp.Compare(uidMap[a], uidMap[b]) |
| 75 |
}) |
| 76 |
} |
| 77 |
|
| 78 |
// SortStringBy sorts the string slice s according to the order given in the |
| 79 |
// order string slice. |
| 80 |
func SortStringBy(s []string, order []string) { |
| 81 |
m := make(map[string]int) |
| 82 |
for i, d := range order { |
| 83 |
m[d] = i |
| 84 |
} |
| 85 |
slices.SortFunc(s, func(a, b string) int { |
| 86 |
return cmp.Compare(m[a], m[b]) |
| 87 |
}) |
| 88 |
} |