converter/cmd/units.go

70 lines
1.5 KiB
Go
Raw Normal View History

2023-02-28 07:37:21 +00:00
package cmd
import (
"fmt"
"strconv"
"strings"
u "github.com/bcicen/go-units"
"github.com/spf13/cobra"
)
// unitsCmd represents the units command
var unitsCmd = &cobra.Command{
Use: "units FROM TO VALUE",
Aliases: []string{"u", "unit"},
Short: "converts your value from and to your given units",
Long: `will search for units matching from and to and convert your value accordingly`,
Args: cobra.MatchAll(cobra.ExactArgs(3), cobra.OnlyValidArgs),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) >= 2 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getUnitNames(toComplete), cobra.ShellCompDirectiveNoFileComp
},
Run: func(cmd *cobra.Command, args []string) {
in, err := strconv.ParseFloat(args[2], 64)
if err != nil {
fmt.Println(err.Error())
return
}
fromVal, err := u.Find(args[0])
if err != nil {
fmt.Println(err.Error())
return
}
toVal, err := u.Find(args[1])
if err != nil {
fmt.Println(err.Error())
return
}
val := u.NewValue(in, fromVal)
out, err := val.Convert(toVal)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(out.String())
},
}
func getUnitNames(in string) []string {
out := []string{}
for _, name := range u.All() {
if in == "" {
out = append(out, name.Names()...)
} else {
for _, n := range name.Names() {
if strings.HasPrefix(n, in) {
out = append(out, n)
}
}
}
}
return out
}
func init() {
rootCmd.AddCommand(unitsCmd)
}