diff --git a/main.go b/main.go index 4b6c993..651bc76 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,13 @@ func bail(status int, t string, args ...interface{}) { os.Exit(status) } +func wrap(err error, t string, args ...interface{}) error { + if err == io.EOF { + return io.EOF + } + return fmt.Errorf(t+": %v", append(args, err)...) +} + type options struct { b bool // bzip compression flag v bool // verbose flag @@ -45,7 +52,7 @@ func (o options) input() (io.Reader, error) { } else { fi, err := os.Open(o.f) if err != nil { - return nil, fmt.Errorf("unable to open file %s: %v", o.f, err) + return nil, wrap(err, "unable to open file %s", o.f) } r = fi } @@ -72,5 +79,7 @@ func main() { if err := p.start(); err != nil { bail(1, "parse error: %v", err) } - p.run() + if err := p.run(); err != nil && err != io.EOF { + bail(1, "run error: %v", err) + } } diff --git a/parser.go b/parser.go index c4c5519..4372ce2 100644 --- a/parser.go +++ b/parser.go @@ -4,7 +4,6 @@ import ( "bufio" "fmt" "io" - // "github.com/golang/protobuf/proto" ) type parser struct { @@ -23,23 +22,22 @@ func newParser(r io.Reader) *parser { func (p *parser) start() error { ok, err := p.checkHeader() if err != nil { - return fmt.Errorf("parser start error: %v", err) + return wrap(err, "parser start error") } if !ok { return fmt.Errorf("parser start error: invalid header") } if _, err := p.source.Discard(8); err != nil { - return err + return wrap(err, "parser start error") } return nil } -func (p *parser) run() { +func (p *parser) run() error { for { msg, err := p.readMessage() if err != nil { - fmt.Printf("error: %v\n", err) - return + return wrap(err, "read message error in run loop") } fmt.Println(msg) } @@ -58,7 +56,7 @@ func (p *parser) decodeVarint() (uint64, error) { // would require 10 bytes. buf, err := p.source.Peek(10) if err != nil { - return 0, fmt.Errorf("decode varint couldn't peek 9 bytes: %v", err) + return 0, wrap(err, "decode varint couldn't peek 10 bytes") } var x uint64 @@ -67,7 +65,7 @@ func (p *parser) decodeVarint() (uint64, error) { // when msb is 0, we're at the last byte of the value if b < 0x80 { if _, err := p.source.Discard(i + 1); err != nil { - return 0, fmt.Errorf("decode varint couldn't discard %d bytes: %v", i, err) + return 0, wrap(err, "decode varint couldn't discard %d bytes", i) } return x | uint64(b)< 0 { buf, err := p.readn(int(size)) if err != nil { - return nil, fmt.Errorf("readMessage couldn't read message body: %v", err) + return nil, wrap(err, "readMessage couldn't read message body") } return &message{cmd, int64(tick), compressed, buf}, nil }