diff --git a/cmd/main.go b/cmd/main.go index ac0c38f..9bb302a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,15 +2,32 @@ package main import ( "flag" + "os" "ronnyfriedland/timetracker/v2/internal/cli" ) func main() { - mode := flag.String("mode", "cli", "the application mode, available: cli") - configPath := flag.String("configpath", "/var/lib/timetracker", "the config path") - flag.Parse() - - if *mode == "cli" { - cli.Run(configPath) + mode, configPath := parseArguments() + if mode == "" { + os.Exit(0) + } else if mode == "cli" { + cli.Run(&configPath) + os.Exit(0) + } else { + os.Exit(1) + } +} + +func parseArguments() (string, string) { + mode := flag.String("mode", "cli", "the application mode, available: cli") + configPath := flag.String("configpath", "/var/lib/timetracker", "the config path") + help := flag.Bool("help", false, "print this help message") + flag.Parse() + + if *help { + flag.PrintDefaults() + return "", "" + } else { + return *mode, *configPath } } diff --git a/cmd/main_test.go b/cmd/main_test.go new file mode 100644 index 0000000..b909b74 --- /dev/null +++ b/cmd/main_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "flag" + "log" + "os" + "testing" +) + +func TestParameter(t *testing.T) { + oldArgs := os.Args + defer func() { os.Args = oldArgs }() + + params := []string{"-configpath", "/foo", "-mode", "testmode"} + + flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError) + os.Args = append([]string{"params"}, params...) + + mode, configPath := parseArguments() + if mode != "testmode" { + log.Fatalf("Got unexpected mode result, got %s, expected %s", "testmode", mode) + } + if configPath != "/foo" { + log.Fatalf("Got unexpected config path result, got %s, expected %s", "/foo", configPath) + } +} + +func TestParameterDefaults(t *testing.T) { + oldArgs := os.Args + defer func() { os.Args = oldArgs }() + + params := []string{} + + flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError) + os.Args = append([]string{"defaults"}, params...) + + mode, configPath := parseArguments() + if mode != "cli" { + log.Fatalf("Got unexpected mode result, got %s, expected %s", "cli", mode) + } + if configPath != "/var/lib/timetracker" { + log.Fatalf("Got unexpected config path result, got %s, expected %s", "/var/lib/timetracker", configPath) + } +} + +func TestParameterHelp(t *testing.T) { + oldArgs := os.Args + defer func() { os.Args = oldArgs }() + + params := []string{"-help"} + + flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError) + os.Args = append([]string{"help"}, params...) + + mode, configPath := parseArguments() + if mode != "" { + log.Fatalf("Got unexpected mode result, got %s, expected %s", "", mode) + } + if configPath != "" { + log.Fatalf("Got unexpected config path result, got %s, expected %s", "", configPath) + } +}