From 13d9c41af3e00e70840929a9533f77dbc5a8957a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20H=C3=A5rek=20Andreassen?= Date: Fri, 4 Oct 2024 20:51:20 +0200 Subject: [PATCH] refactor: Move output json to helper func MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tim HĂ„rek Andreassen --- cmd/forecast.go | 6 +----- cmd/forecast_helper.go | 13 ++++++++++--- cmd/now.go | 6 +----- cmd/today.go | 6 +----- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/cmd/forecast.go b/cmd/forecast.go index 35d33b1..abfbba7 100644 --- a/cmd/forecast.go +++ b/cmd/forecast.go @@ -1,7 +1,6 @@ package cmd import ( - "encoding/json" "fmt" "git.sr.ht/~timharek/yr/cmd/flags" @@ -37,10 +36,7 @@ func forecast(cmd *cobra.Command, args []string) { } if helper.isJson { - j, err := json.MarshalIndent(f, "", " ") - cobra.CheckErr(err) - fmt.Printf("%s", j) - return + outputJson(f.Forecast) } t := table.New() diff --git a/cmd/forecast_helper.go b/cmd/forecast_helper.go index cbaf343..f83ac1d 100644 --- a/cmd/forecast_helper.go +++ b/cmd/forecast_helper.go @@ -1,6 +1,7 @@ package cmd import ( + "encoding/json" "fmt" "os" @@ -57,8 +58,14 @@ func forecastHelper(cmd *cobra.Command, args []string) *forecastH { func openBrowser(u string, f *yr.ForecastResult) { url := fmt.Sprintf(u, f.Coordinates.Latitude, f.Coordinates.Longitude) err := browser.OpenURL(url) - if err != nil { - cobra.CheckErr(err) - } + cobra.CheckErr(err) + os.Exit(0) +} + +// Returns forecast in pretty printed JSON and exits +func outputJson(v any) { + j, err := json.MarshalIndent(v, "", " ") + cobra.CheckErr(err) + fmt.Printf("%s\n", j) os.Exit(0) } diff --git a/cmd/now.go b/cmd/now.go index 2c0d455..f2418ca 100644 --- a/cmd/now.go +++ b/cmd/now.go @@ -1,7 +1,6 @@ package cmd import ( - "encoding/json" "fmt" "github.com/spf13/cobra" @@ -30,10 +29,7 @@ func now(cmd *cobra.Command, args []string) { n := f.Forecast[0] if helper.isJson { - j, err := json.MarshalIndent(f, "", " ") - cobra.CheckErr(err) - fmt.Printf("%s", j) - return + outputJson(n) } itemTime := n.Time.Local() diff --git a/cmd/today.go b/cmd/today.go index 7369d0c..fe0fabd 100644 --- a/cmd/today.go +++ b/cmd/today.go @@ -1,7 +1,6 @@ package cmd import ( - "encoding/json" "fmt" "time" @@ -29,10 +28,7 @@ func today(cmd *cobra.Command, args []string) { } if helper.isJson { - j, err := json.MarshalIndent(f, "", " ") - cobra.CheckErr(err) - fmt.Printf("%s", j) - return + outputJson(f.Forecast) } t := table.New()