add prompts for add cmd

This commit is contained in:
Callan Bryant 2020-03-02 02:16:53 +00:00
parent 27e0fcf327
commit bba8662ab9
No known key found for this signature in database
GPG Key ID: C31FA9DF3ACBFFAA
2 changed files with 52 additions and 12 deletions

View File

@ -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":

43
util.go
View File

@ -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.")
}
}