converter/cmd/time.go

96 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-02-28 08:36:11 +00:00
package cmd
import (
"fmt"
2023-02-28 16:00:47 +00:00
"os"
2023-02-28 08:36:11 +00:00
"strings"
"time"
2023-02-28 16:00:47 +00:00
"unicode"
2023-02-28 08:36:11 +00:00
"github.com/spf13/cobra"
)
var timeCmd = &cobra.Command{
Use: "time",
Short: "gets current time in given city",
Long: `gets current time in given city`,
2023-02-28 08:59:26 +00:00
Args: cobra.MatchAll(cobra.RangeArgs(1, 2), cobra.OnlyValidArgs),
2023-02-28 08:36:11 +00:00
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
2023-02-28 16:00:47 +00:00
return getOsTimeZones(toComplete), cobra.ShellCompDirectiveNoFileComp
2023-02-28 08:36:11 +00:00
},
RunE: func(cmd *cobra.Command, args []string) error {
loc, _ := time.LoadLocation(args[0])
2023-02-28 08:59:26 +00:00
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"))
2023-02-28 08:36:11 +00:00
return nil
},
}
2023-02-28 16:00:47 +00:00
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)
2023-02-28 08:36:11 +00:00
} else {
2023-02-28 16:00:47 +00:00
zones = append(zones, newPath)
2023-02-28 08:36:11 +00:00
}
}
2023-02-28 16:00:47 +00:00
return zones
2023-02-28 08:36:11 +00:00
}
func init() {
rootCmd.AddCommand(timeCmd)
}