factor out argument checking into function

This commit is contained in:
nytpu
2021-03-18 14:30:07 -06:00
parent 1065ed7a18
commit 2487727329
+17 -25
View File
@@ -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 {