yr/cmd/now.go
Tim Hårek Andreassen c5cb76a731
chore: Better times
Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
2024-10-03 22:48:50 +02:00

91 lines
1.8 KiB
Go

package cmd
import (
"encoding/json"
"fmt"
"os"
"git.sr.ht/~timharek/yr/cmd/flags"
"git.sr.ht/~timharek/yr/internal/nominatim"
"git.sr.ht/~timharek/yr/yr"
"github.com/pkg/browser"
"github.com/spf13/cobra"
)
var nowCmd = &cobra.Command{
Use: "now <location>",
Aliases: []string{"current", "n"},
Short: "Get current forecasted weather",
Args: cobra.MaximumNArgs(1),
Run: now,
}
func init() {
rootCmd.AddCommand(nowCmd)
}
func now(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.NowCoords(&nominatim.Coordinates{Longitude: lon, Latitude: lat}, nil)
cobra.CheckErr(err)
} else {
location := args[0]
f, err = c.Now(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)
}
n := f.Forecast[0]
if isJson {
j, err := json.MarshalIndent(f, "", " ")
cobra.CheckErr(err)
fmt.Printf("%s", j)
return
}
itemTime := n.Time.Local()
if isUTC {
itemTime = n.Time
}
fmt.Printf(
`%s %s:
Temperature: %.1f °C
Rain: %.1f mm
Wind: %.1f m/s from %s
`,
n.Location,
itemTime.Format("Monday 2 Jan 15:04"),
n.Temperature,
n.Percipitation,
n.Wind.Speed,
n.Wind.DirectionToString(),
)
}