package mailq import ( "encoding/json" "fmt" "io" "strings" "text/tabwriter" ) const SortableDateFormat = "2006-01-02 15:04:05" func (m QEntry) String() string { var recipientSuffix string if len(m.Recipients) > 1 { recipientSuffix = ",..." } return fmt.Sprintf("[%s] %s <%s> -> {%d}<%s>%s (%s, %d bytes)", m.Date.Format(SortableDateFormat), m.Id, m.Sender, len(m.Recipients), m.Recipients[0], recipientSuffix, m.Status, m.Size) } func (m QEntry) MachineReadableString() string { return fmt.Sprintf("%s_%s_%s_%d_%s_%s_%s", m.Id, m.Status, m.Date.Format(SortableDateFormat), m.Size, m.Sender, m.Reason, strings.Join(m.Recipients, ",")) } func (m QEntry) DetailedString() string { var reasonStr string if m.Reason == "" { reasonStr = "-/-" } return fmt.Sprintf("Id: %s\nDate: %s\nStatus: %s\nReason: %s\nSize: %d\nSender: %s\nRecipients: {%d} %s", m.Id, m.Date.Format(SortableDateFormat), m.Status, reasonStr, m.Size, m.Sender, len(m.Recipients), strings.Join(m.Recipients, ", ")) } func (queue MailQ) WriteMachineReadable(writer io.Writer) { for _, entry := range queue.Entries { fmt.Fprintf(writer, "%s\n", entry.MachineReadableString()) } } func (queue MailQ) WriteHumanReadable(writer io.Writer) { queue.WriteSummary(writer) if len(queue.Entries) != 0 { fmt.Fprintf(writer, "\n") tabWriter := tabwriter.NewWriter(writer, 2, 2, 1, ' ', tabwriter.TabIndent) fmt.Fprintf(tabWriter, "| %s\t| %s\t| %s\t| %s\t| %s\t| %s\t| %s\t| %s\t| \n", "Date", "Id", "Status", "Size", "Sender", "#", "First Recipient", "Reason") for _, entry := range queue.Entries { _, writeError := fmt.Fprintf(tabWriter, "| %s\t| %s\t| %s\t| %d\t| %s\t| {%d}\t| %s\t| %s\t| \n", entry.Date.Format(SortableDateFormat), entry.Id, entry.Status, entry.Size, entry.Sender, len(entry.Recipients), entry.Recipients[0], entry.Reason) if writeError != nil { // A writeError is expected once the reader was closed break } } tabWriter.Flush() } } func (queue MailQ) WriteSummary(writer io.Writer) { if len(queue.Entries) == 0 { fmt.Fprintf(writer, "Mail queue is empty\n") } else { fmt.Fprintf(writer, "%d entries total (%d active, %d deferred, %d on hold)\n", len(queue.Entries), queue.NumActive, queue.NumDeferred, queue.NumHold) } } func (queue MailQ) WriteJSON(writer io.Writer) { bytes, err := json.Marshal(queue) if err != nil { fmt.Fprintf(writer, "Error encoding queue to JSON: %s\n", err.Error()) } else { fmt.Fprintf(writer, "%s", bytes) } }