Skip to content

Commit 4c42fd0

Browse files
committed
match tail handling of newlines at EOF
1 parent 5f0e9bc commit 4c42fd0

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

cmd/gotail/gotail.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func main() {
3737
}
3838

3939
if n != 0 {
40-
config.LineLocation = &tail.SeekInfo{-n + 1, io.SeekEnd}
40+
config.LineLocation = &tail.SeekInfo{-n, io.SeekEnd}
4141
}
4242

4343
done := make(chan bool)

tail.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,28 @@ func (tail *Tail) tailFileSync() {
254254
}
255255
} else if tail.LineLocation != nil {
256256
lineFile := fls.LineFile(tail.file)
257-
_, err := lineFile.SeekLine(tail.LineLocation.Offset, tail.LineLocation.Whence)
257+
buf := make([]byte, 1)
258+
259+
_, err := lineFile.Seek(-1, io.SeekEnd)
260+
if err != nil {
261+
tail.Killf("Seek error on %s: %s", tail.Filename, err)
262+
return
263+
}
264+
265+
_, err = lineFile.Read(buf)
266+
if err != nil {
267+
tail.Killf("Seek error on %s: %s", tail.Filename, err)
268+
return
269+
}
270+
271+
// if file ends in newline don't count it in lines
272+
// to read from end (mimics unix tail command)
273+
correction := int64(1)
274+
if string(buf) == "\n" {
275+
correction = 0
276+
}
277+
278+
_, err = lineFile.SeekLine(tail.LineLocation.Offset+correction, tail.LineLocation.Whence)
258279
if err != nil && err != io.EOF {
259280
tail.Killf("Seek error on %s: %s", tail.Filename, err)
260281
return

0 commit comments

Comments
 (0)