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)) + } +}