snippets/stamp.go

65 lines
1.1 KiB
Go

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
nano 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.nano {
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.nano, "nano", 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))
}
}