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() { func main() {
if len(os.Args) < 2 { argCheck(os.Args, 2, true, "Please provide a command.")
fmt.Fprint(os.Stderr, "Please provide a command.\n\n")
usage()
os.Exit(1)
}
// these are special cases where we shouldn't bother to do anything else // these are special cases where we shouldn't bother to do anything else
if os.Args[1] == "help" { if os.Args[1] == "help" {
@@ -59,26 +55,15 @@ func main() {
switch os.Args[1] { switch os.Args[1] {
case "refresh": case "refresh":
if len(c.Args()) != 0 { argCheck(c.Args(), 0, false, "'refresh' doesn't take an argument!")
fmt.Fprint(os.Stderr, "\"refresh\" doesn't take an argument!\n\n")
usage()
os.Exit(1)
}
fetch.RefreshAll(&core.Data, *refreshWorkersFlag) fetch.RefreshAll(&core.Data, *refreshWorkersFlag)
case "list": case "list":
if len(c.Args()) != 0 { argCheck(c.Args(), 0, false, "'list' doesn't take an argument!")
fmt.Fprint(os.Stderr, "\"list\" doesn't take an argument!\n\n")
usage()
os.Exit(1)
}
// TODO // TODO
fmt.Fprintln(os.Stderr, "Not Yet Implemented") fmt.Fprintln(os.Stderr, "Not Yet Implemented")
case "add": case "add":
if len(c.Args()) < 1 { argCheck(c.Args(), 1, true, "Please provide a URL to add.")
fmt.Fprint(os.Stderr, "Please provide a URL to add.\n\n")
usage()
os.Exit(1)
}
remote, err := url.Parse(c.Arg(0)) remote, err := url.Parse(c.Arg(0))
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing URL: %v\n", err) fmt.Fprintf(os.Stderr, "Error parsing URL: %v\n", err)
@@ -94,11 +79,7 @@ func main() {
os.Exit(1) os.Exit(1)
} }
case "remove": case "remove":
if len(c.Args()) < 1 { argCheck(c.Args(), 1, true, "Please provide a URL to remove.")
fmt.Fprint(os.Stderr, "Please provide a URL to remove.\n\n")
usage()
os.Exit(1)
}
// TODO // TODO
fmt.Fprintln(os.Stderr, "Not Yet Implemented") 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. // verifyPath will expand ~ if neccessary and will clean the path.
func verifyPath(p string) string { func verifyPath(p string) string {
if n, err := homedir.Expand(p); err != nil { if n, err := homedir.Expand(p); err != nil {