From 0ed31eb73b13bd57aff727f4ab759c6701d45a01 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Daniel=20Mart=C3=AD?= Date: Fri, 18 Mar 2022 10:57:02 +0000 Subject: [PATCH] cmd/gofmt: return a proper error for empty Go files MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit I was testing edge cases in gofumpt, a fork of gofmt, and noticed that gofmt will return a bare io error on empty files, as demonstrated by the added test case without a fix: > ! exec $GOROOT/bin/gofmt empty.go nopackage.go [stderr] EOF nopackage.go:1:1: expected 'package', found not The problem is the code that detects concurrent modifications. It relies on ReadFull and correctly deals with io.ErrUnexpectedEOF, but it did not pay attention to io.EOF, which can happen when size==0. Change-Id: I6092391721edad4584fb5922d3e3a8fb3da86493 Reviewed-on: https://go-review.googlesource.com/c/go/+/393757 Run-TryBot: Daniel Martí Trust: Matt Layher Reviewed-by: Robert Griesemer Trust: Daniel Martí TryBot-Result: Gopher Robot --- src/cmd/go/testdata/script/fmt_load_errors.txt | 7 +++++++ src/cmd/gofmt/gofmt.go | 7 ++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/cmd/go/testdata/script/fmt_load_errors.txt b/src/cmd/go/testdata/script/fmt_load_errors.txt index 559dcc5fe3..e3a9034ede 100644 --- a/src/cmd/go/testdata/script/fmt_load_errors.txt +++ b/src/cmd/go/testdata/script/fmt_load_errors.txt @@ -16,6 +16,10 @@ stdout 'package x' exec $GOROOT/bin/gofmt gofmt-dir ! stdout 'package x' +! exec $GOROOT/bin/gofmt empty.go nopackage.go +stderr -count=1 'empty\.go:1:1: expected .package., found .EOF.' +stderr -count=1 'nopackage\.go:1:1: expected .package., found not' + -- exclude/empty/x.txt -- -- exclude/ignore/_x.go -- package x @@ -29,3 +33,6 @@ package x package x -- gofmt-dir/no-extension -- package x +-- empty.go -- +-- nopackage.go -- +not the proper start to a Go file diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index 8efc88df88..5fa883fb56 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -347,7 +347,12 @@ func readFile(filename string, info fs.FileInfo, in io.Reader) ([]byte, error) { // stop to avoid corrupting it.) src := make([]byte, size+1) n, err := io.ReadFull(in, src) - if err != nil && err != io.ErrUnexpectedEOF { + switch err { + case nil, io.EOF, io.ErrUnexpectedEOF: + // io.ReadFull returns io.EOF (for an empty file) or io.ErrUnexpectedEOF + // (for a non-empty file) if the file was changed unexpectedly. Continue + // with comparing file sizes in those cases. + default: return nil, err } if n < size { -- 2.50.0