From 7afa99f7d5eb66538274d24e5823f500a4f46890 Mon Sep 17 00:00:00 2001 From: Hugo Bally Date: Mon, 14 Nov 2022 13:14:41 +0100 Subject: [PATCH] Fix Issue #16 - Change openpomodoro client init The --directory flag does not work, all commands use the default `~/.pomodoro` directory even when the flag is provided. With the current code, `directoryFlag` is always an empty string when passed to the openpomodoro.NewClient function because the flag has not been parsed yet at this time. Moving to the PersistentPreRun hook ensures that all commands will initialize the client with the correct flag value. Co-authored-by: hugobally --- cmd/root.go | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 0be0557..8308e4b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -11,22 +11,35 @@ import ( "github.com/spf13/viper" ) -// RootCmd represents the base command when called without any subcommands -var RootCmd = &cobra.Command{ - Use: "pomodoro", - Short: "Pomodoro CLI", - Long: "A simple Pomodoro command-line client for the Open Pomodoro format", -} - var ( client *openpomodoro.Client - settings *openpomodoro.Settings + settings = &openpomodoro.DefaultSettings directoryFlag string formatFlag string waitFlag bool ) +// RootCmd represents the base command when called without any subcommands +var RootCmd = &cobra.Command{ + Use: "pomodoro", + Short: "Pomodoro CLI", + Long: "A simple Pomodoro command-line client for the Open Pomodoro format", + PersistentPreRun: func(cmd *cobra.Command, args []string) { + var err error + + client, err = openpomodoro.NewClient(directoryFlag) + if err != nil { + log.Fatalf("Could not create client: %v", err) + } + + settings, err = client.Settings() + if err != nil { + log.Fatalf("Could not retrieve settings: %v", err) + } + }, +} + func init() { cobra.OnInitialize(initConfig) @@ -43,18 +56,6 @@ func init() { "wait for the Pomodoro to end before exiting") viper.AutomaticEnv() - - var err error - - client, err = openpomodoro.NewClient(directoryFlag) - if err != nil { - log.Fatalf("Could not create client: %v", err) - } - - settings, err = client.Settings() - if err != nil { - log.Fatalf("Could not retrieve settings: %v", err) - } } func initConfig() {