Skip to content

Commit c07ec39

Browse files
Tarmigan Caseboltgriesemer
Tarmigan Casebolt
authored andcommitted
go/printer: avoid stomping on err before checking it
Change-Id: I97ba31e758d3396842ad99a08af696e49a5f1a7d Reviewed-on: https://go-review.googlesource.com/13954 Run-TryBot: Robert Griesemer <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Robert Griesemer <[email protected]>
1 parent 7454f53 commit c07ec39

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/go/printer/printer.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1178,7 +1178,9 @@ func (p *trimmer) Write(data []byte) (n int, err error) {
11781178
case '\n', '\f':
11791179
_, err = p.output.Write(data[m:n])
11801180
p.resetSpace()
1181-
_, err = p.output.Write(aNewline)
1181+
if err == nil {
1182+
_, err = p.output.Write(aNewline)
1183+
}
11821184
case tabwriter.Escape:
11831185
_, err = p.output.Write(data[m:n])
11841186
p.state = inEscape

src/go/printer/printer_test.go

+41
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"go/ast"
1313
"go/parser"
1414
"go/token"
15+
"io"
1516
"io/ioutil"
1617
"path/filepath"
1718
"testing"
@@ -548,6 +549,46 @@ func f()
548549
}
549550
}
550551

552+
type limitWriter struct {
553+
remaining int
554+
errCount int
555+
}
556+
557+
func (l *limitWriter) Write(buf []byte) (n int, err error) {
558+
n = len(buf)
559+
if n >= l.remaining {
560+
n = l.remaining
561+
err = io.EOF
562+
l.errCount++
563+
}
564+
l.remaining -= n
565+
return n, err
566+
}
567+
568+
// Test whether the printer stops writing after the first error
569+
func TestWriteErrors(t *testing.T) {
570+
const filename = "printer.go"
571+
src, err := ioutil.ReadFile(filename)
572+
if err != nil {
573+
panic(err) // error in test
574+
}
575+
file, err := parser.ParseFile(fset, filename, src, 0)
576+
if err != nil {
577+
panic(err) // error in test
578+
}
579+
for i := 0; i < 20; i++ {
580+
lw := &limitWriter{remaining: i}
581+
err := (&Config{Mode: RawFormat}).Fprint(lw, fset, file)
582+
if lw.errCount > 1 {
583+
t.Fatal("Writes continued after first error returned")
584+
}
585+
// We expect errCount be 1 iff err is set
586+
if (lw.errCount != 0) != (err != nil) {
587+
t.Fatal("Expected err when errCount != 0")
588+
}
589+
}
590+
}
591+
551592
// TextX is a skeleton test that can be filled in for debugging one-off cases.
552593
// Do not remove.
553594
func TestX(t *testing.T) {

0 commit comments

Comments
 (0)