mailq-inspector/shell.go

115 lines
2.7 KiB
Go

package main
import (
"bufio"
"fmt"
"io"
"strings"
)
import (
"mailq-inspector/mailq"
)
type shellState struct {
SortConfig mailq.QEntrySortConfig
QuitShell bool
Queue mailq.MailQ
}
func initialShellState() shellState {
var state shellState = shellState{}
state.QuitShell = false
state.SortConfig = defaultSortConfig()
state = refreshQueue(state)
return state
}
func refreshQueue(state shellState) shellState {
queue, err := fetchQueue()
if err != nil {
fmt.Printf("Error fetching queue: '%s'\n", err.Error())
}
state.Queue = queue
return state
}
func updateSortConfig(fields []string, state shellState) shellState {
sortConfig := mailq.NewSortConfig()
var err error
for _, field := range fields[1:] {
split := strings.Split(field, ":")
sortConfig, err = sortConfig.By(split[0], split[1])
if err != nil {
fmt.Printf("Error applying sort config: '%s'\n", err.Error())
}
}
state.SortConfig = sortConfig
return state
}
func displayMessageDetails(fields []string, writer io.Writer, state shellState) {
if len(fields) < 2 {
fmt.Fprintln(writer, "Please state the Id of the message to inspect!")
return
}
messageId := fields[1]
message, err := state.Queue.GetMessageById(messageId)
if err != nil {
fmt.Fprintf(writer, "Could not inspect message with id '%s': '%s'\n", messageId, err.Error())
} else {
fmt.Fprintf(writer, "%s\n", message.DetailedString())
}
}
func interactiveShell(reader io.Reader, writer io.Writer) {
var state shellState = initialShellState()
fmt.Fprintln(writer, "Let's try an interactive shell!")
scanner := bufio.NewScanner(reader)
for {
fmt.Fprint(writer, "> ")
if !scanner.Scan() {
fmt.Println()
break
}
text := strings.Trim(scanner.Text(), " ")
textFields := strings.Fields(text)
if len(textFields) == 0 {
continue
}
cmd := textFields[0]
switch cmd {
case "help", "?":
printHelp(writer)
case "exit":
state.QuitShell = true
case "inspect":
displayMessageDetails(textFields, writer, state)
case "sort":
state = updateSortConfig(textFields, state)
case "show":
state.Queue.Sort(state.SortConfig)
displayQueue(state.Queue)
case "summary":
state.Queue.WriteSummary(writer)
case "reload":
state = refreshQueue(state)
fmt.Fprintln(writer, "Queue data reloaded")
state.Queue.WriteSummary(writer)
default:
fmt.Fprintf(writer, "Unknown command '%s'\n", cmd)
fmt.Fprintln(writer, "Use 'help' to display help command")
}
if state.QuitShell == true {
break
}
}
fmt.Fprintln(writer, "\nGoodbye!\n")
}
func printHelp(writer io.Writer) {
fmt.Fprintln(writer, "Available commands:")
fmt.Fprintln(writer, "?, help: display this output")
fmt.Fprintln(writer, "exit: quit this program")
}