converter/cmd/temp.go
2023-02-27 22:45:19 -08:00

78 lines
2.0 KiB
Go

package cmd
import (
"fmt"
"strconv"
"strings"
u "github.com/bcicen/go-units"
"github.com/spf13/cobra"
)
var (
from string
to string
tempCmd = &cobra.Command{
Use: "temperature",
Aliases: []string{"temp", "t", "temps"},
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Args: cobra.MatchAll(cobra.ExactArgs(1)),
RunE: func(cmd *cobra.Command, args []string) error {
err := cmd.ParseFlags(args)
if err != nil {
return err
}
in, err := strconv.ParseFloat(args[0], 64)
if err != nil {
return err
}
fromFlag := strings.ToLower(cmd.Flag("from").Value.String())
toFlag := strings.ToLower(cmd.Flag("to").Value.String())
var out u.Value
switch fromFlag {
case "f", "farenheit":
out, err = Convert(in, toFlag, u.Fahrenheit)
if err != nil {
return err
}
case "c", "celsius":
out, err = Convert(in, toFlag, u.Celsius)
if err != nil {
return err
}
case "k", "kelvin":
out, err = Convert(in, toFlag, u.Kelvin)
if err != nil {
return err
}
}
fmt.Println(out.String())
return nil
},
}
)
func Convert(in float64, to string, from u.Unit) (u.Value, error) {
switch to {
case "f", "farenheit":
return u.ConvertFloat(in, from, u.Fahrenheit)
case "c", "celsius":
return u.ConvertFloat(in, from, u.Celsius)
case "k", "kelvin":
return u.ConvertFloat(in, from, u.Kelvin)
}
return u.Value{}, fmt.Errorf("Invalid flags provided")
}
func init() {
rootCmd.AddCommand(tempCmd)
tempCmd.PersistentFlags().StringVarP(&from, "from", "f", "c", "unit system to convert from, (farenheit, celsius, kelvin)")
tempCmd.PersistentFlags().StringVarP(&to, "to", "t", "f", "unit system to convert to, (farenheit, celsius, kelvin)")
}