From f96d33cf0dc8d1c77a257f2093f2c7479562f209 Mon Sep 17 00:00:00 2001 From: gutmet Date: Wed, 21 Oct 2020 16:13:21 +0200 Subject: [PATCH] stamp.go: solo timestamps or for each line in stdin --- stamp.go | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 stamp.go diff --git a/stamp.go b/stamp.go new file mode 100644 index 0000000..4beb140 --- /dev/null +++ b/stamp.go @@ -0,0 +1,64 @@ +package main + +import ( + "bufio" + "flag" + "fmt" + "os" + "time" +) + +const ( + defaultFormat = "2006-01-02 15:04:05" + filenameFormat = "20060102-150405" +) + +type flags struct { + utc bool + filename bool + precise bool +} + +func stamp(format string, f *flags) string { + t := time.Now() + if f.utc { + t = t.UTC() + } + return t.Format(format) +} + +func getFormat(f *flags) string { + var format string + if f.filename { + format = filenameFormat + } else { + format = defaultFormat + } + if f.precise { + format += ".000000000" + } + return format +} + +func main() { + f := flags{} + flag.BoolVar(&f.utc, "utc", false, "use UTC instead of local time") + flag.BoolVar(&f.filename, "filename", false, "use filename friendly format") + flag.BoolVar(&f.precise, "precise", false, "include nanoseconds") + flag.Parse() + + format := getFormat(&f) + + stat, _ := os.Stdin.Stat() + if (stat.Mode() & os.ModeCharDevice) == 0 { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + fmt.Println(stamp(format, &f), scanner.Text()) + } + if err := scanner.Err(); err != nil { + panic(err) + } + } else { + fmt.Println(stamp(format, &f)) + } +}