From 248772732932cfb2560381200daf6f63b5fa3a07 Mon Sep 17 00:00:00 2001 From: nytpu Date: Thu, 18 Mar 2021 14:30:07 -0600 Subject: [PATCH] factor out argument checking into function --- comitium.go | 42 +++++++++++++++++------------------------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/comitium.go b/comitium.go index d837b64..cdb5aaf 100644 --- a/comitium.go +++ b/comitium.go @@ -19,11 +19,7 @@ import ( ) func main() { - if len(os.Args) < 2 { - fmt.Fprint(os.Stderr, "Please provide a command.\n\n") - usage() - os.Exit(1) - } + argCheck(os.Args, 2, true, "Please provide a command.") // these are special cases where we shouldn't bother to do anything else if os.Args[1] == "help" { @@ -59,26 +55,15 @@ func main() { switch os.Args[1] { case "refresh": - if len(c.Args()) != 0 { - fmt.Fprint(os.Stderr, "\"refresh\" doesn't take an argument!\n\n") - usage() - os.Exit(1) - } + argCheck(c.Args(), 0, false, "'refresh' doesn't take an argument!") fetch.RefreshAll(&core.Data, *refreshWorkersFlag) case "list": - if len(c.Args()) != 0 { - fmt.Fprint(os.Stderr, "\"list\" doesn't take an argument!\n\n") - usage() - os.Exit(1) - } + argCheck(c.Args(), 0, false, "'list' doesn't take an argument!") // TODO fmt.Fprintln(os.Stderr, "Not Yet Implemented") case "add": - if len(c.Args()) < 1 { - fmt.Fprint(os.Stderr, "Please provide a URL to add.\n\n") - usage() - os.Exit(1) - } + argCheck(c.Args(), 1, true, "Please provide a URL to add.") + remote, err := url.Parse(c.Arg(0)) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing URL: %v\n", err) @@ -94,11 +79,7 @@ func main() { os.Exit(1) } case "remove": - if len(c.Args()) < 1 { - fmt.Fprint(os.Stderr, "Please provide a URL to remove.\n\n") - usage() - os.Exit(1) - } + argCheck(c.Args(), 1, true, "Please provide a URL to remove.") // TODO fmt.Fprintln(os.Stderr, "Not Yet Implemented") } @@ -110,6 +91,17 @@ func main() { } } +// argCheck makes sure that the target number of arguments are given. If +// not, msg is displayed alongside usage information and then the program exits +// with failure. +func argCheck(args []string, target int, lt bool, msg string) { + if (lt && len(args) < target) || (!lt && len(args) != target) { + fmt.Fprint(os.Stderr, msg, "\n\n") + usage() + os.Exit(1) + } +} + // verifyPath will expand ~ if neccessary and will clean the path. func verifyPath(p string) string { if n, err := homedir.Expand(p); err != nil {