yr/cmd/now.go
Tim Hårek Andreassen d7d8ce6cd9
feat: Add coordinates to CLI
Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
2024-09-29 21:46:34 +02:00

65 lines
1.2 KiB
Go

package cmd
import (
"encoding/json"
"fmt"
"os"
"git.sr.ht/~timharek/yr-go/internal/nominatim"
"git.sr.ht/~timharek/yr-go/yr"
"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("json")
cobra.CheckErr(err)
lon, _ := cmd.Flags().GetFloat64("lon")
lat, _ := cmd.Flags().GetFloat64("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)
}
n := &yr.NowForecast{}
if len(args) == 0 {
n, err = c.NowCoords(&nominatim.Coordinates{Longitude: lon, Latitude: lat}, nil)
cobra.CheckErr(err)
} else {
location := args[0]
n, err = c.Now(location)
cobra.CheckErr(err)
}
if isJson {
j, err := json.MarshalIndent(n, "", " ")
cobra.CheckErr(err)
fmt.Printf("%s", j)
return
}
fmt.Printf(
`Current forecast for %s
Temperature: %.1f
Rain: %.1f`,
n.Location,
n.Temperature,
n.Percipitation,
)
}