From f0c8d7d24fb96645a8804ce805f034e7e2fba8a0 Mon Sep 17 00:00:00 2001 From: Siarhiej Siemianczuk Date: Tue, 23 Jul 2024 19:44:45 +0300 Subject: [PATCH] cmds/core/head: use io.ReadFull for reading bytes Signed-off-by: Siarhiej Siemianczuk --- cmds/core/head/head.go | 6 ++++-- cmds/core/head/head_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cmds/core/head/head.go b/cmds/core/head/head.go index d15a1b587c..4f3d11625a 100644 --- a/cmds/core/head/head.go +++ b/cmds/core/head/head.go @@ -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 } diff --git a/cmds/core/head/head_test.go b/cmds/core/head/head_test.go index 55cf2db27a..1935dbd946 100644 --- a/cmds/core/head/head_test.go +++ b/cmds/core/head/head_test.go @@ -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"))