81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
u "github.com/bcicen/go-units"
|
|
"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
|
|
}
|
|
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)")
|
|
}
|