From 8ca26b3d9d66425c7b95118977612e181ee03c8f Mon Sep 17 00:00:00 2001 From: Jan Philipp Timme Date: Sat, 29 Dec 2018 22:02:23 +0100 Subject: [PATCH] Refactoring --- main.go | 27 ++++++++++++++++----------- parser/parser.go | 4 +++- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/main.go b/main.go index a7eae7d..7277f94 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,6 @@ package main import ( - "bufio" "flag" "fmt" "os" @@ -16,8 +15,12 @@ var settings = make(map[string]string) func argParse() { inputModePtr := flag.String("inputMode", "stdin", "How to get mailq output. Available options: \"stdin\", 'cmd'") + mailqCommandPtr := flag.String("mailqCommand", "mailq", "Command to use for getting mailq output") + mailqCommandArgsPtr := flag.String("mailqCommandArgs", "", "Optional arguments to pass to mailqCommand") flag.Parse() settings["inputMode"] = *inputModePtr + settings["mailqCommand"] = *mailqCommandPtr + settings["mailqCommandArgs"] = *mailqCommandArgsPtr } func main() { @@ -27,7 +30,7 @@ func main() { if settings["inputMode"] == "stdin" { entries, err = readFromStdin() } else if settings["inputMode"] == "cmd" { - entries, err = readFromCmd(exec.Command("mailq")) + entries, err = readFromCmd(exec.Command(settings["mailqCommand"])) } else { fmt.Printf("Unsupported inputMode!") flag.PrintDefaults() @@ -45,18 +48,20 @@ func main() { } func readFromStdin() ([]parser.QEntry, error) { - scanner := bufio.NewScanner(os.Stdin) - return parser.ParseMailQ(scanner) + return parser.ParseMailQ(os.Stdin) } func readFromCmd(cmd *exec.Cmd) ([]parser.QEntry, error) { stdout, err := cmd.StdoutPipe() - err = cmd.Start() - scanner := bufio.NewScanner(stdout) - result, resErr := parser.ParseMailQ(scanner) - err = cmd.Wait() - if err != nil { - fmt.Printf("Oh no: %s", err.Error()) + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, err + } + result, resultError := parser.ParseMailQ(stdout) + if err := cmd.Wait(); err != nil { + return nil, err } - return result, resErr + return result, resultError } diff --git a/parser/parser.go b/parser/parser.go index 391edf2..abfd1b7 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -4,6 +4,7 @@ import ( "bufio" "errors" "fmt" + "io" "regexp" "strconv" "strings" @@ -24,9 +25,10 @@ func (m QEntry) String() string { return fmt.Sprintf("ID: %s, Status: %s, Size: %d bytes, Sender: %s, Recipients: %d", m.id, m.status, m.size, m.sender, len(m.recipients)) } -func ParseMailQ(scanner *bufio.Scanner) ([]QEntry, error) { +func ParseMailQ(dataSource io.Reader) ([]QEntry, error) { const dateFormat = "2006 Mon Jan _2 15:04:05" var messageIdStart = regexp.MustCompile("^[0-9A-Za-z]+[*!]? ") + scanner := bufio.NewScanner(dataSource) scanner.Scan() line := scanner.Text() if strings.HasPrefix(line, "Mail queue is empty") {