Use reader and writer to make shell extensible

This commit is contained in:
Jan Philipp Timme 2019-01-01 19:37:05 +01:00
parent b471f6a914
commit f7bb218403
2 changed files with 24 additions and 10 deletions

View File

@ -21,7 +21,7 @@ func main() {
showQueue() showQueue()
} }
if settings["interactive"] == "true" { if settings["interactive"] == "true" {
interactiveShell() interactiveShell(os.Stdin, os.Stdout)
} }
} }

View File

@ -3,15 +3,17 @@ package main
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io"
"os" "os"
"strings" "strings"
) )
func interactiveShell() { func interactiveShell(reader io.Reader, writer io.Writer) {
fmt.Println("Let's try an interactive shell!") fmt.Fprintln(writer, "Let's try an interactive shell!")
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(reader)
for { for {
fmt.Print("> ") var quitShell bool = false
fmt.Fprint(writer, "> ")
if !scanner.Scan() { if !scanner.Scan() {
break break
} }
@ -21,14 +23,26 @@ func interactiveShell() {
continue continue
} }
cmd := textFields[0] cmd := textFields[0]
fmt.Printf("Read input: %q\n", textFields) fmt.Fprintf(writer, "DEBUG - Read input: %q\n", textFields)
switch cmd { switch cmd {
case "help", "?":
printHelp(os.Stdout)
case "exit", "quit":
quitShell = true
default: default:
fmt.Printf("Unknown command '%s'\n", cmd) fmt.Fprintf(writer, "Unknown command '%s'\n", cmd)
fmt.Fprintln(writer, "Use 'help' to display help command")
}
if quitShell == true {
break
}
}
fmt.Fprintln(writer, "\nGoodbye!\n")
} }
} func printHelp(writer io.Writer) {
fmt.Println("\nGoodbye!\n") fmt.Fprintln(writer, "Available commands:")
fmt.Fprintln(writer, "?, help: display this output")
fmt.Fprintln(writer, "exit, quit: quit this program")
} }