mailq-inspector/shell.go

99 lines
2.2 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 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", "quit":
state.QuitShell = true
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: quit this program")
}