converter/cmd/time.go
2023-02-28 08:00:47 -08:00

96 lines
1.8 KiB
Go

package cmd
import (
"fmt"
"os"
"strings"
"time"
"unicode"
"github.com/spf13/cobra"
)
var timeCmd = &cobra.Command{
Use: "time",
Short: "gets current time in given city",
Long: `gets current time in given city`,
Args: cobra.MatchAll(cobra.RangeArgs(1, 2), cobra.OnlyValidArgs),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getOsTimeZones(toComplete), cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error {
loc, _ := time.LoadLocation(args[0])
if len(args) == 2 {
t, err := time.Parse("03:04PM", args[1])
if err != nil {
return err
}
fmt.Println(t.In(loc).Format("03:04PM"))
return nil
}
fmt.Println(time.Now().In(loc).Format("03:04PM"))
return nil
},
}
func getOsTimeZones(toComplete string) []string {
var zones []string
zoneDirs := []string{
"/usr/share/zoneinfo/",
"/usr/share/lib/zoneinfo/",
"/usr/lib/locale/TZ/",
}
for _, zd := range zoneDirs {
zones = walkTzDir(zd, zones)
for idx, zone := range zones {
zones[idx] = strings.ReplaceAll(zone, zd+"/", "")
}
}
return zones
}
func isAlpha(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) {
return false
}
}
return true
}
func walkTzDir(path string, zones []string) []string {
fileInfos, err := os.ReadDir(path)
if err != nil {
return zones
}
for _, info := range fileInfos {
if info.Name() != strings.ToUpper(info.Name()[:1])+info.Name()[1:] {
continue
}
if !isAlpha(info.Name()[:1]) {
continue
}
newPath := path + "/" + info.Name()
if info.IsDir() {
zones = walkTzDir(newPath, zones)
} else {
zones = append(zones, newPath)
}
}
return zones
}
func init() {
rootCmd.AddCommand(timeCmd)
}