From bba8662ab99c064995f6fc560701e56cbb60093a Mon Sep 17 00:00:00 2001 From: Callan Bryant Date: Mon, 2 Mar 2020 02:16:53 +0000 Subject: [PATCH] add prompts for add cmd --- cmd/dsnet.go | 21 +++++++++------------ util.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 12 deletions(-) diff --git a/cmd/dsnet.go b/cmd/dsnet.go index 4a9caa9..be6ed8a 100644 --- a/cmd/dsnet.go +++ b/cmd/dsnet.go @@ -2,7 +2,6 @@ package main import ( "os" - "flag" "fmt" "github.com/naggie/dsnet" ) @@ -10,14 +9,6 @@ import ( func main() { var cmd string - addCmd := flag.NewFlagSet("add", flag.ExitOnError) - hostname := addCmd.String("hostname", "", "Hostname of device") - owner := addCmd.String("owner", "", "Username of owner of device") - description := addCmd.String("description", "", "Information about device") - publicKey := addCmd.String("publicKey", "", "Optional existing public key of device") - - - if len(os.Args) == 1 { cmd = "help" } else { @@ -29,9 +20,15 @@ func main() { dsnet.Init() case "add": - addCmd.PrintDefaults() - addCmd.Parse(os.Args[2:]) - dsnet.Add(*hostname, *owner, *description, *publicKey) + // TODO maybe accept flags to avoid prompt and allow programmatic use + hostname := dsnet.MustPromptString("Hostname", true) + owner := dsnet.MustPromptString("owner", true) + description := dsnet.MustPromptString("Description", true) + publicKey := dsnet.MustPromptString("PublicKey (optional)", false) + + dsnet.ConfirmOrAbort("\nDo you want to add the above configuration?") + + dsnet.Add(hostname, owner, description, publicKey) case "up": diff --git a/util.go b/util.go index a551dda..5c70f51 100644 --- a/util.go +++ b/util.go @@ -1,7 +1,50 @@ package dsnet +import ( + "os" + "bufio" + "strings" + "fmt" +) + func check(e error) { if e != nil { panic(e) } } + +func MustPromptString(prompt string, required bool) string { + reader := bufio.NewReader(os.Stdin) + var text string + var err error + + for text == "" { + fmt.Printf("%s: ", prompt) + text, err = reader.ReadString('\n') + check(err) + text = strings.TrimSpace(text) + } + return text +} + +func ExitFail(format string, a ...interface{}) { + fmt.Fprintf(os.Stderr, "\033[31m"+format+"\033[0m\n", a...) + os.Exit(1) +} + +func ConfirmOrAbort(format string, a ...interface{}) { + fmt.Fprintf(os.Stderr, format+" [y/n] ", a...) + + reader := bufio.NewReader(os.Stdin) + + input, err := reader.ReadString('\n') + if err != nil { + panic(err) + } + + if input == "y\n" { + return + } else { + ExitFail("Aborted.") + } +}