From 3a37c29de49109c729b048d735a4cd2784824a38 Mon Sep 17 00:00:00 2001 From: nxshock Date: Sat, 8 Apr 2023 14:02:36 +0500 Subject: [PATCH] Autodetect datetime format --- main.go | 23 +++-------------------- utils.go | 15 +++++++++++++++ utils_test.go | 19 +++++++++++++++++++ 3 files changed, 37 insertions(+), 20 deletions(-) diff --git a/main.go b/main.go index 2b9a74f..0b1f8ca 100644 --- a/main.go +++ b/main.go @@ -4,7 +4,6 @@ import ( "log" "os" "path/filepath" - "time" ) func init() { @@ -56,25 +55,9 @@ func main() { log.Fatalln(err) } - var t time.Time - switch len(os.Args[4]) { - case len("02.01.2006"): - t, err = time.Parse("02.01.2006 15:04", os.Args[4]) - if err != nil { - config.fatalln("time parse error:", err) - } - case len("02.01.2006 15:04"): - t, err = time.Parse("02.01.2006 15:04", os.Args[4]) - if err != nil { - config.fatalln("time parse error:", err) - } - case len("02.01.2006 15:04:05"): - t, err = time.Parse("02.01.2006 15:04:05", os.Args[4]) - if err != nil { - config.fatalln("time parse error:", err) - } - default: - config.fatalln(`wrong time format, must be ["DD.MM.YYYY", "DD.MM.YYYY hh:mm", "DD.MM.YYYY hh:mm:ss"]`) + t, err := parseTime(os.Args[4]) + if err != nil { + config.fatalln(err) } plan, err := config.extractionPlan(os.Args[3], t) diff --git a/utils.go b/utils.go index a6566b0..7ec8a8c 100644 --- a/utils.go +++ b/utils.go @@ -1,9 +1,11 @@ package main import ( + "errors" "fmt" "path/filepath" "strings" + "time" "github.com/tidwall/match" ) @@ -71,3 +73,16 @@ func isFilePathMatchPatterns(patterns []string, fileName string) bool { return false } + +func parseTime(s string) (time.Time, error) { + switch len(s) { + case len("02.01.2006"): + return time.ParseInLocation("02.01.2006", s, time.Local) + case len("02.01.2006 15:04"): + return time.ParseInLocation("02.01.2006 15:04", s, time.Local) + case len("02.01.2006 15:04:05"): + return time.ParseInLocation("02.01.2006 15:04:05", s, time.Local) + } + + return time.Time{}, errors.New("unknown time format") +} diff --git a/utils_test.go b/utils_test.go index 6bad3fc..3769cd4 100644 --- a/utils_test.go +++ b/utils_test.go @@ -2,6 +2,7 @@ package main import ( "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -10,3 +11,21 @@ func TestSizeToApproxHuman(t *testing.T) { assert.Equal(t, "1.0 KiB", sizeToApproxHuman(1024)) assert.Equal(t, "1.1 KiB", sizeToApproxHuman(1126)) } + +func TestParseTime(t *testing.T) { + tests := []struct { + input string + expected time.Time + }{ + {"02.01.2006", time.Date(2006, 01, 02, 0, 0, 0, 0, time.Local)}, + {"02.01.2006 15:04", time.Date(2006, 01, 02, 15, 4, 0, 0, time.Local)}, + {"02.01.2006 15:04:05", time.Date(2006, 01, 02, 15, 4, 5, 0, time.Local)}, + } + + for _, test := range tests { + got, err := parseTime(test.input) + assert.NoError(t, err) + + assert.Equal(t, test.expected, got) + } +}