Commit d22b5735 authored by Agniva De Sarker's avatar Agniva De Sarker Committed by Agniva De Sarker

cmd/doc: show the package clause always

If no writes to the package buffer happen, then the package clause
does not get printed. This is a bug for cases where a file just contains
the package clause.

We fix this by separating the printing of package clause to a new
function and calling it from (*pkgBuffer).Write as well as (*Package).flush.

Updates #31457

Change-Id: Ia3bd0ea3963274c460a45d1e37fafc6ee0a197f0
Reviewed-on: https://go-review.googlesource.com/c/go/+/206128
Run-TryBot: Agniva De Sarker <agniva.quicksilver@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: default avatarRob Pike <r@golang.org>
parent 194ae323
...@@ -211,6 +211,13 @@ var tests = []test{ ...@@ -211,6 +211,13 @@ var tests = []test{
`func \(unexportedType\)`, `func \(unexportedType\)`,
}, },
}, },
// Package with just the package declaration. Issue 31457.
{
"only package declaration",
[]string{"-all", p + "/nested/empty"},
[]string{`package empty .*import`},
nil,
},
// Package dump -short // Package dump -short
{ {
"full package with -short", "full package with -short",
......
...@@ -53,14 +53,18 @@ type pkgBuffer struct { ...@@ -53,14 +53,18 @@ type pkgBuffer struct {
} }
func (pb *pkgBuffer) Write(p []byte) (int, error) { func (pb *pkgBuffer) Write(p []byte) (int, error) {
if !pb.printed && len(p) > 0 { pb.packageClause()
return pb.Buffer.Write(p)
}
func (pb *pkgBuffer) packageClause() {
if !pb.printed {
pb.printed = true pb.printed = true
// Only show package clause for commands if requested explicitly. // Only show package clause for commands if requested explicitly.
if pb.pkg.pkg.Name != "main" || showCmd { if pb.pkg.pkg.Name != "main" || showCmd {
pb.pkg.packageClause() pb.pkg.packageClause()
} }
} }
return pb.Buffer.Write(p)
} }
type PackageError string // type returned by pkg.Fatalf. type PackageError string // type returned by pkg.Fatalf.
...@@ -210,6 +214,8 @@ func (pkg *Package) Printf(format string, args ...interface{}) { ...@@ -210,6 +214,8 @@ func (pkg *Package) Printf(format string, args ...interface{}) {
} }
func (pkg *Package) flush() { func (pkg *Package) flush() {
// Print the package clause in case it wasn't written already.
pkg.buf.packageClause()
_, err := pkg.writer.Write(pkg.buf.Bytes()) _, err := pkg.writer.Write(pkg.buf.Bytes())
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment