Skip to content

Commit

Permalink
cmds/core/head: use io.ReadFull for reading bytes
Browse files Browse the repository at this point in the history
Signed-off-by: Siarhiej Siemianczuk <[email protected]>
  • Loading branch information
binjip978 committed Jul 24, 2024
1 parent d3e1220 commit f0c8d7d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cmds/core/head/head.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ func run(stdout io.Writer, stderr io.Writer, bytes, count int, files ...string)
}
}
if printBytes {
n, err := f.Read(buffer)
if err != nil {
n, err := io.ReadFull(f, buffer)
if err == io.ErrUnexpectedEOF {
// ignore if user request more bytes than file has
} else if err != nil {
fmt.Fprintf(stderr, "head: %v", err)
continue
}
Expand Down
14 changes: 14 additions & 0 deletions cmds/core/head/head_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,20 @@ func TestHead(t *testing.T) {
}
})

t.Run("request more bytes", func(t *testing.T) {
stdout := &bytes.Buffer{}
err := run(stdout, nil, 10000, 0, f1.Name())
if err != nil {
t.Fatalf("expected nil, got %v", err)
}

expected := "f11\nf12\nf13\nf14\nf15"

if stdout.String() != expected {
t.Errorf("%v != %v", expected, stdout.String())
}
})

t.Run("file not exists", func(t *testing.T) {
stderr := &bytes.Buffer{}
err := run(nil, stderr, 0, 0, filepath.Join(dir, "filenotexists"))
Expand Down

0 comments on commit f0c8d7d

Please sign in to comment.