mailq-inspector/mailq/sorting.go

108 lines
2.7 KiB
Go
Raw Permalink Normal View History

2019-01-01 16:02:04 +01:00
package mailq
import (
"errors"
2019-01-01 16:02:04 +01:00
"fmt"
"sort"
)
2019-01-01 21:23:04 +01:00
type QSortConfig struct {
2019-01-01 16:02:04 +01:00
attributes []qEntryAttributeSortConfig
}
type qEntryAttributeSortConfig struct {
attribute string
order string
}
2019-01-01 21:23:04 +01:00
func NewSortConfig() QSortConfig {
return QSortConfig{}
2019-01-01 16:02:04 +01:00
}
func isQEntryAttribute(attributeName string) bool {
var isValidAttribute bool
switch attributeName {
case "Id", "Status", "Date", "Size", "Sender", "Recipients", "Reason":
isValidAttribute = true
default:
isValidAttribute = false
}
return isValidAttribute
}
2019-01-01 21:23:04 +01:00
func (c QSortConfig) By(attributeName string, order string) (QSortConfig, error) {
2019-01-01 16:02:04 +01:00
if !isQEntryAttribute(attributeName) {
return c, errors.New(fmt.Sprintf("Invalid sort attribute: '%s' given!", attributeName))
2019-01-01 16:02:04 +01:00
}
if order != "ASC" && order != "DESC" {
return c, errors.New(fmt.Sprintf("Invalid sort order '%s' given!", order))
2019-01-01 16:02:04 +01:00
}
newAttributeConfig := qEntryAttributeSortConfig{attribute: attributeName, order: order}
c.attributes = append(c.attributes, newAttributeConfig)
return c, nil
2019-01-01 16:02:04 +01:00
}
2019-01-01 21:23:04 +01:00
func (queue MailQ) Sort(config QSortConfig) {
2019-01-01 16:02:04 +01:00
if len(config.attributes) == 0 {
return
}
sort.Slice(queue.Entries, func(a int, b int) bool {
for _, sortBy := range config.attributes {
var cmp bool
var skip bool
// Not sure if these are necessary yet
cmp = false
skip = false
switch sortBy.attribute {
case "Id":
if queue.Entries[a].Id == queue.Entries[b].Id {
skip = true
}
cmp = queue.Entries[a].Id < queue.Entries[b].Id
case "Status":
if queue.Entries[a].Status == queue.Entries[b].Status {
skip = true
}
cmp = queue.Entries[a].Status < queue.Entries[b].Status
case "Date":
if queue.Entries[a].Date.Equal(queue.Entries[b].Date) {
skip = true
}
cmp = queue.Entries[a].Date.Before(queue.Entries[b].Date)
case "Size":
if queue.Entries[a].Size == queue.Entries[b].Size {
skip = true
}
cmp = queue.Entries[a].Size < queue.Entries[b].Size
case "Sender":
if queue.Entries[a].Sender == queue.Entries[b].Sender {
skip = true
}
cmp = queue.Entries[a].Sender < queue.Entries[b].Sender
case "Recipients":
if len(queue.Entries[a].Recipients) == len(queue.Entries[b].Recipients) {
skip = true
}
cmp = len(queue.Entries[a].Recipients) < len(queue.Entries[b].Recipients)
case "Reason":
if queue.Entries[a].Reason == queue.Entries[b].Reason {
skip = true
}
cmp = queue.Entries[a].Reason < queue.Entries[b].Reason
default:
// TODO: Handle this error case?
}
if skip == true {
continue
} else {
if sortBy.order == "ASC" {
return cmp
} else if sortBy.order == "DESC" {
return !cmp
}
}
}
return false
})
}