Validate args passed - fail fast in case of invalid args (#79)
diff --git a/cmd/set.go b/cmd/set.go index 0cc1bf1..fef9b3f 100644 --- a/cmd/set.go +++ b/cmd/set.go
@@ -21,6 +21,7 @@ "fmt" "reflect" "strings" + "errors" "github.com/apache/cloudstack-cloudmonkey/config" ) @@ -33,7 +34,7 @@ "prompt": {"🐵", "🐱", "random"}, "asyncblock": {"true", "false"}, "timeout": {"600", "1800", "3600"}, - "output": {"json", "text", "table", "column", "csv"}, + "output": config.GetOutputFormats(), "profile": {}, "url": {}, "username": {}, @@ -56,6 +57,15 @@ fmt.Println("Usage: set <subcommand> <option>. Press tab-tab to see available subcommands and options.") return nil } + if subCommand == "display" { + subCommand = "output" + } + validArgs := r.Command.SubCommands[subCommand] + if len(validArgs) != 0 && subCommand != "timeout" { + if !config.CheckIfValuePresent(validArgs, value) { + return errors.New("Invalid value set for " + subCommand +". Supported values: " + strings.Join(validArgs, ", ") ) + } + } r.Config.UpdateConfig(subCommand, value, true) if subCommand == "profile" && r.Config.HasShell {
diff --git a/cmk.go b/cmk.go index eb94999..b614b95 100644 --- a/cmk.go +++ b/cmk.go
@@ -41,7 +41,8 @@ } func main() { - outputFormat := flag.String("o", "", "output format: json, text, table, column, csv") + validFormats := strings.Join(config.GetOutputFormats(), ",") + outputFormat := flag.String("o", "", "output format: " + validFormats) showVersion := flag.Bool("v", false, "show version") debug := flag.Bool("d", false, "enable debug mode") profile := flag.String("p", "", "server profile") @@ -61,6 +62,10 @@ } if *outputFormat != "" { + if !config.CheckIfValuePresent(config.GetOutputFormats(), *outputFormat) { + fmt.Println("Invalid value set for output format. Supported values: " + validFormats) + os.Exit(1) + } cfg.UpdateConfig("output", *outputFormat, false) }
diff --git a/config/config.go b/config/config.go index 592438a..b64832e 100644 --- a/config/config.go +++ b/config/config.go
@@ -74,6 +74,18 @@ ActiveProfile *ServerProfile } +func GetOutputFormats() []string { + return []string {"column", "csv", "json", "table", "text"} +} + +func CheckIfValuePresent(dataset []string, element string) bool { + for _, arg := range dataset { + if arg == element { + return true + } + } + return false +} // CacheFile returns the path to the cache file for a server profile func (c Config) CacheFile() string { cacheDir := path.Join(c.Dir, "profiles")