converter/cmd/root.go
2023-02-27 23:13:56 -08:00

63 lines
1.3 KiB
Go

package cmd
import (
"fmt"
"os"
"strconv"
u "github.com/bcicen/go-units"
"github.com/spf13/cobra"
)
var (
from string
to string
rootCmd = &cobra.Command{
Use: "converter FROM TO VALUE",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. 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(3)),
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 Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
rootCmd.InitDefaultHelpFlag()
rootCmd.Flags().MarkHidden("help")
}