Using bufio reader for Stdin, otherwise the first 3 bytes are consumed and file gets "corrupted" (stdin is not seekable?)

This commit is contained in:
Samuel Archambault
2019-12-04 15:32:12 -05:00
committed by Simarpreet Singh
parent 9bf16ae1ba
commit 2cb920d5d9
3 changed files with 12 additions and 9 deletions

View File

@@ -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 {

View File

@@ -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

View File

@@ -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)
}