From 2cb920d5d9c0ba97e5fe38b29fd255d76a932ce6 Mon Sep 17 00:00:00 2001 From: Samuel Archambault Date: Wed, 4 Dec 2019 15:32:12 -0500 Subject: [PATCH] Using bufio reader for Stdin, otherwise the first 3 bytes are consumed and file gets "corrupted" (stdin is not seekable?) --- analyzer/analyzer.go | 9 ++++++--- utils/utils.go | 9 ++++----- utils/utils_test.go | 3 ++- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/analyzer/analyzer.go b/analyzer/analyzer.go index 040cce39ed..c247624ce1 100644 --- a/analyzer/analyzer.go +++ b/analyzer/analyzer.go @@ -1,6 +1,7 @@ package analyzer import ( + "bufio" "compress/gzip" "context" "io" @@ -136,12 +137,14 @@ func (ac Config) Analyze(ctx context.Context, imageName string, opts ...types.Do func (ac Config) AnalyzeFile(ctx context.Context, f *os.File) (fileMap extractor.FileMap, err error) { var r io.Reader - r = f - if utils.IsGzip(f) { - r, err = gzip.NewReader(f) + br := bufio.NewReader(f) + if utils.IsGzip(br) { + r, err = gzip.NewReader(br) if err != nil { return nil, xerrors.Errorf("failed to open gzip: %w", err) } + } else { + r = br } fileMap, err = ac.Extractor.ExtractFromFile(ctx, r, RequiredFilenames()) if err != nil { diff --git a/utils/utils.go b/utils/utils.go index 5bca7fcddb..665206e9af 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -1,8 +1,8 @@ package utils import ( + "bufio" "fmt" - "io" "os" "os/exec" "path/filepath" @@ -37,11 +37,10 @@ func IsCommandAvailable(name string) bool { return true } -func IsGzip(f *os.File) bool { +func IsGzip(f *bufio.Reader) bool { buf := make([]byte, 3) - n, _ := f.Read(buf) - defer f.Seek(0, io.SeekStart) - if n < 3 { + buf, err := f.Peek(3) + if err != nil { return false } return buf[0] == 0x1F && buf[1] == 0x8B && buf[2] == 0x8 diff --git a/utils/utils_test.go b/utils/utils_test.go index f6dbe34361..4adbb46b2e 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -1,6 +1,7 @@ package utils import ( + "bufio" "os" "testing" ) @@ -23,7 +24,7 @@ func TestIsGzip(t *testing.T) { t.Fatalf("unknown error: %s", err) } - got := IsGzip(f) + got := IsGzip(bufio.NewReader(f)) if got != tt.want { t.Errorf("got %t, want %t", got, tt.want) }