converter/cmd/temp.go

81 lines
2.1 KiB
Go
Raw Normal View History

2023-02-28 06:12:00 +00:00
package cmd
import (
"fmt"
"strconv"
"strings"
2023-02-28 06:32:34 +00:00
u "github.com/bcicen/go-units"
2023-02-28 06:12:00 +00:00
"github.com/spf13/cobra"
)
var (
from string
to string
five_over_nine = float64(5) / float64(9)
nine_over_five = float64(9) / float64(5)
kconst = 273.15
rconst = 459.67
tempCmd = &cobra.Command{
Use: "temp",
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
}
2023-02-28 06:32:34 +00:00
fromFlag := strings.ToLower(cmd.Flag("from").Value.String())
toFlag := strings.ToLower(cmd.Flag("to").Value.String())
var out u.Value
switch fromFlag {
2023-02-28 06:12:00 +00:00
case "f", "farenheit":
2023-02-28 06:32:34 +00:00
out, err = Convert(in, toFlag, u.Fahrenheit)
if err != nil {
return err
2023-02-28 06:12:00 +00:00
}
case "c", "celsius":
2023-02-28 06:32:34 +00:00
out, err = Convert(in, toFlag, u.Celsius)
if err != nil {
return err
2023-02-28 06:12:00 +00:00
}
case "k", "kelvin":
2023-02-28 06:32:34 +00:00
out, err = Convert(in, toFlag, u.Kelvin)
if err != nil {
return err
2023-02-28 06:12:00 +00:00
}
}
2023-02-28 06:32:34 +00:00
fmt.Println(out.String())
2023-02-28 06:12:00 +00:00
return nil
},
}
)
2023-02-28 06:32:34 +00:00
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")
}
2023-02-28 06:12:00 +00:00
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)")
}