From f1aa9cbf16e86dd40a954c1ee9fb180d3d4c31d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20H=C3=A5rek=20Andreassen?= Date: Thu, 3 Oct 2024 22:45:55 +0200 Subject: [PATCH] feat: Add today command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tim Hårek Andreassen --- cmd/today.go | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 cmd/today.go diff --git a/cmd/today.go b/cmd/today.go new file mode 100644 index 0000000..1ba8e12 --- /dev/null +++ b/cmd/today.go @@ -0,0 +1,91 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "time" + + "git.sr.ht/~timharek/yr/cmd/flags" + "git.sr.ht/~timharek/yr/cmd/internal/ui/table" + "git.sr.ht/~timharek/yr/internal/nominatim" + "git.sr.ht/~timharek/yr/yr" + "github.com/pkg/browser" + "github.com/spf13/cobra" +) + +var todayCmd = &cobra.Command{ + Use: "today ", + Aliases: []string{"twm", "trm"}, + Short: "Get tomorrow's forecasted weather", + Args: cobra.MaximumNArgs(1), + Run: today, +} + +func init() { + rootCmd.AddCommand(todayCmd) +} + +func today(cmd *cobra.Command, args []string) { + isJson, err := cmd.Flags().GetBool(flags.JSON) + cobra.CheckErr(err) + isUTC, err := cmd.Flags().GetBool(flags.UTC) + cobra.CheckErr(err) + isWeb, err := cmd.Flags().GetBool(flags.WEB) + cobra.CheckErr(err) + lon, _ := cmd.Flags().GetFloat64(flags.LON) + lat, _ := cmd.Flags().GetFloat64(flags.LAT) + + c, err := yr.New() + cobra.CheckErr(err) + + if len(args) == 0 && (lon == 0 || lat == 0) { + fmt.Fprintln(os.Stderr, "No location or coordinates provided.") + os.Exit(1) + } + f := &yr.ForecastResult{} + if len(args) == 0 { + f, err = c.ForecastCoords(&nominatim.Coordinates{Longitude: lon, Latitude: lat}, nil) + cobra.CheckErr(err) + } else { + location := args[0] + f, err = c.Forecast(location) + cobra.CheckErr(err) + } + + if isWeb { + url := fmt.Sprintf("https://www.yr.no/en/forecast/hourly-table/%.4f,%.4f?i=0", f.Coordinates.Latitude, f.Coordinates.Longitude) + err := browser.OpenURL(url) + if err != nil { + cobra.CheckErr(err) + } + os.Exit(0) + } + + if isJson { + j, err := json.MarshalIndent(f, "", " ") + cobra.CheckErr(err) + fmt.Printf("%s", j) + return + } + + t := table.New() + + today := time.Now() + for _, item := range f.Forecast { + if item.Time.Format(time.DateOnly) != today.Format(time.DateOnly) { + continue + } + itemTime := item.Time.Local() + if isUTC { + itemTime = item.Time + } + t.Row( + itemTime.Format("15:04"), + fmt.Sprintf("%.1f °C", item.Temperature), + fmt.Sprintf("%.1f mm", item.Percipitation), + fmt.Sprintf("%.1f m/s %s", item.Wind.Speed, item.Wind.DirectionToString()), + ) + } + fmt.Println(t) +}