From 3d893015a3136eb4805c228164b16f4e547a6d7a Mon Sep 17 00:00:00 2001 From: Jan Philipp Timme Date: Mon, 31 Dec 2018 21:22:23 +0100 Subject: [PATCH] Add support for JSON output --- main.go | 12 +++++++----- parser/parser.go | 10 ++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 26bca7e..5d99744 100644 --- a/main.go +++ b/main.go @@ -29,13 +29,13 @@ func parseArguments() { mailqCommandPtr := flag.String("mailqCommand", "mailq", "Command to use for getting mailq output") mailqCommandArgsPtr := flag.String("mailqCommandArgs", "", "Optional arguments to pass to mailqCommand") interactivePtr := flag.Bool("interactive", false, "Set to true for shell mode") - machineFormatPtr := flag.Bool("machineFormat", false, "Set to true to get output suitable for cut/awk/...") + outputFormatPtr := flag.String("outputFormat", "human", "Available output formats: \"human\", \"machine\", \"json\"") usePagerPtr := flag.Bool("usePager", true, "Use pager to display output?") flag.Parse() settings["mailqCommand"] = *mailqCommandPtr settings["mailqCommandArgs"] = *mailqCommandArgsPtr settings["interactive"] = strconv.FormatBool(*interactivePtr) - settings["machineFormat"] = strconv.FormatBool(*machineFormatPtr) + settings["outputFormat"] = *outputFormatPtr settings["usePager"] = strconv.FormatBool(*usePagerPtr) } @@ -63,10 +63,12 @@ func showQueue() { } func printQueue(queue parser.MailQ, writer io.Writer) { - if settings["machineFormat"] == "true" { - queue.PrintMachineReadable(writer) - } else { + if settings["outputFormat"] == "human" { queue.PrintHumanReadable(writer) + } else if settings["outputFormat"] == "machine" { + queue.PrintMachineReadable(writer) + } else if settings["outputFormat"] == "json" { + queue.PrintJSON(writer) } } diff --git a/parser/parser.go b/parser/parser.go index a5b2d9a..8f576b8 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -2,6 +2,7 @@ package parser import ( "bufio" + "encoding/json" "errors" "fmt" "io" @@ -76,6 +77,15 @@ func (queue MailQ) PrintHumanReadable(writer io.Writer) { } } +func (queue MailQ) PrintJSON(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) + } +} + func ParseMailQ(dataSource io.Reader) (MailQ, error) { const dateFormat = "2006 Mon Jan _2 15:04:05" var messageIdStart = regexp.MustCompile("^[0-9A-Za-z]+[*!]? ")