Implement simple parsering
This commit is contained in:
75
main.go
Normal file
75
main.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
logger "git.site.quack-lab.dev/dave/cylogger"
|
||||
)
|
||||
|
||||
type DateParser interface {
|
||||
Parse(s string) (time.Time, error)
|
||||
}
|
||||
|
||||
type DateParser8 struct {
|
||||
re *regexp.Regexp
|
||||
}
|
||||
|
||||
func (dp *DateParser8) Parse(s string) (time.Time, error) {
|
||||
matches := dp.re.FindStringSubmatch(s)
|
||||
if len(matches) == 0 {
|
||||
return time.Time{}, fmt.Errorf("no match")
|
||||
}
|
||||
return time.Parse("20060102", matches[0])
|
||||
}
|
||||
|
||||
type DateParserISO struct {
|
||||
re *regexp.Regexp
|
||||
}
|
||||
|
||||
func (dp *DateParserISO) Parse(s string) (time.Time, error) {
|
||||
matches := dp.re.FindStringSubmatch(s)
|
||||
if len(matches) == 0 {
|
||||
return time.Time{}, fmt.Errorf("no match")
|
||||
}
|
||||
return time.Parse("2006-01-02", matches[0])
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
logger.InitFlag()
|
||||
|
||||
if flag.NArg() == 0 {
|
||||
logger.Error("no files provided")
|
||||
return
|
||||
}
|
||||
|
||||
parsers := []DateParser{
|
||||
&DateParser8{re: regexp.MustCompile(`\d{8}`)},
|
||||
&DateParserISO{re: regexp.MustCompile(`\d{4}-\d{2}-\d{2}`)},
|
||||
}
|
||||
|
||||
files := flag.Args()
|
||||
|
||||
for _, file := range files {
|
||||
logger.Info("processing file: %s", file)
|
||||
date, err := parseDate(file, parsers)
|
||||
if err != nil {
|
||||
logger.Error("error parsing date: %s", err)
|
||||
continue
|
||||
}
|
||||
logger.Info("date: %s", date)
|
||||
}
|
||||
}
|
||||
|
||||
func parseDate(file string, parsers []DateParser) (time.Time, error) {
|
||||
for _, parser := range parsers {
|
||||
date, err := parser.Parse(file)
|
||||
if err == nil {
|
||||
return date, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("no date found")
|
||||
}
|
Reference in New Issue
Block a user