converter/cmd/root.go

62 lines
1.4 KiB
Go
Raw Normal View History

2023-02-28 06:12:00 +00:00
package cmd
import (
2023-02-28 07:04:05 +00:00
"fmt"
2023-02-28 06:12:00 +00:00
"os"
2023-02-28 07:04:05 +00:00
"strconv"
2023-02-28 06:12:00 +00:00
2023-02-28 07:04:05 +00:00
u "github.com/bcicen/go-units"
2023-02-28 06:12:00 +00:00
"github.com/spf13/cobra"
)
2023-02-28 07:04:05 +00:00
var (
from string
to string
rootCmd = &cobra.Command{
Use: "converter",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
2023-02-28 06:12:00 +00:00
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.`,
2023-02-28 07:04:05 +00:00
Run: func(cmd *cobra.Command, args []string) {
in, err := strconv.ParseFloat(args[0], 64)
if err != nil {
fmt.Println(err.Error())
return
}
fromVal, err := u.Find(cmd.Flag("from").Value.String())
if err != nil {
fmt.Println(err.Error())
return
}
toVal, err := u.Find(cmd.Flag("to").Value.String())
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())
},
}
)
2023-02-28 06:12:00 +00:00
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
2023-02-28 07:04:05 +00:00
func init() {
rootCmd.PersistentFlags().StringVarP(&from, "from", "f", "c", "unit system to convert from")
rootCmd.PersistentFlags().StringVarP(&to, "to", "t", "f", "unit system to convert to")
}