Skip to content

Commit 164f04a

Browse files
committed
match tail handling of newlines at EOF
1 parent 5f0e9bc commit 164f04a

1 file changed

Lines changed: 28 additions & 4 deletions

File tree

cmd/gotail/gotail.go

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,36 @@ func main() {
3636
os.Exit(1)
3737
}
3838

39-
if n != 0 {
40-
config.LineLocation = &tail.SeekInfo{-n + 1, io.SeekEnd}
41-
}
42-
4339
done := make(chan bool)
4440
for _, filename := range flag.Args() {
41+
42+
if n != 0 {
43+
file, err := os.Open(filename)
44+
if err != nil {
45+
fmt.Println(err)
46+
return
47+
}
48+
49+
buf := make([]byte, 1)
50+
info, err := file.Stat()
51+
if err == nil && info.Size() > 0 {
52+
_, err = file.ReadAt(buf, info.Size()-1)
53+
}
54+
55+
if err != nil {
56+
fmt.Println(err)
57+
return
58+
}
59+
60+
// if file ends in newline dont count it against -n
61+
offset := int64(1)
62+
if string(buf) == "\n" {
63+
offset = 0
64+
}
65+
config.LineLocation = &tail.SeekInfo{-n + offset, io.SeekEnd}
66+
file.Close()
67+
}
68+
4569
go tailFile(filename, config, done)
4670
}
4771

0 commit comments

Comments
 (0)