Refactoring

This commit is contained in:
Jan Philipp Timme 2018-12-29 22:02:23 +01:00
parent 874d000879
commit 8ca26b3d9d
2 changed files with 19 additions and 12 deletions

25
main.go
View File

@ -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())
return nil, err
}
return result, resErr
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, resultError
}

View File

@ -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") {