stamp.go: solo timestamps or for each line in stdin
This commit is contained in:
parent
34056e170a
commit
f96d33cf0d
64
stamp.go
Normal file
64
stamp.go
Normal file
|
@ -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))
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user