From f22be8fccff9f0afb9a06a5e5d51c95b9ca7a877 Mon Sep 17 00:00:00 2001 From: Jan Philipp Timme Date: Tue, 1 Jan 2019 14:36:50 +0100 Subject: [PATCH] Introduce configurable sorting --- main.go | 3 ++- parser/parser.go | 28 +++++++++++++++++++++++----- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 37cd8e6..0980738 100644 --- a/main.go +++ b/main.go @@ -49,7 +49,8 @@ func showQueue() { fmt.Printf("Could not fetch queue entries: %s\n", err.Error()) os.Exit(1) } - queue.Sort() + sortConfig := parser.NewSortConfig().By("Status", "ASC").By("Sender", "ASC").By("Recipients", "DESC") + queue.Sort(sortConfig) if settings["usePager"] == "true" { pagerReader, pagerWriter := io.Pipe() pagerDone := make(chan bool) diff --git a/parser/parser.go b/parser/parser.go index 015ef7c..4359b7b 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -54,14 +54,32 @@ func (m QEntry) DetailedString() string { return fmt.Sprintf("Id: %s\nDate: %s\nStatus: %s\nReason: %s\nSize: %d\nSender: %s\nRecipients: %s", m.Id, m.Date.Format(SortableDateFormat), m.Status, reasonStr, m.Size, m.Sender, strings.Join(m.Recipients, ", ")) } -func (queue MailQ) Sort() { - var sortByAttributes []string = []string{"Status", "Recipients", "Sender", "Date"} - if len(sortByAttributes) == 0 { +type qEntrySortConfig struct { + attributes []qEntryAttributeSortConfig +} + +type qEntryAttributeSortConfig struct { + attribute string + order string +} + +func NewSortConfig() qEntrySortConfig { + return qEntrySortConfig{} +} + +func (c qEntrySortConfig) By(field string, order string) qEntrySortConfig { + newAttributeConfig := qEntryAttributeSortConfig{attribute: field, order: order} + c.attributes = append(c.attributes, newAttributeConfig) + return c +} + +func (queue MailQ) Sort(config qEntrySortConfig) { + if len(config.attributes) == 0 { return } sort.Slice(queue.Entries, func(a int, b int) bool { - for _, sortBy := range sortByAttributes { - switch sortBy { + for _, sortBy := range config.attributes { + switch sortBy.attribute { case "Id": if queue.Entries[a].Id != queue.Entries[b].Id { return queue.Entries[a].Id < queue.Entries[b].Id