Skip to content

Commit

Permalink
cmd/doc: make comments inside functions appear with -src
Browse files Browse the repository at this point in the history
The old godoc didn't do this either, perhaps because it's a little
tricky, but it can be done using a special type from the go/printer
package. (Usually we just use go/format).

Fixes #28195.

Change-Id: Ic6d3df3953ba71128398ceaf9a133c798551b6b8
Reviewed-on: https://go-review.googlesource.com/c/143037
Reviewed-by: Robert Griesemer <gri@golang.org>
  • Loading branch information
robpike committed Oct 18, 2018
1 parent 4158734 commit e0a97a5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/cmd/doc/doc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,8 @@ var tests = []test{
[]string{
`Comment about exported type`, // Include comment.
`type ExportedType struct`, // Type definition.
`Comment before exported field.*\n.*ExportedField +int` +
`.*Comment on line with exported field`,
`Comment before exported field`,
`ExportedField.*Comment on line with exported field`,
`ExportedEmbeddedType.*Comment on line with exported embedded field`,
`unexportedType.*Comment on line with unexported embedded field`,
`func \(ExportedType\) ExportedMethod\(a int\) bool`,
Expand Down
13 changes: 12 additions & 1 deletion src/cmd/doc/pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"go/doc"
"go/format"
"go/parser"
"go/printer"
"go/token"
"io"
"log"
Expand Down Expand Up @@ -206,7 +207,17 @@ func (pkg *Package) newlines(n int) {
// clears the stuff we don't want to print anyway. It's a bit of a magic trick.
func (pkg *Package) emit(comment string, node ast.Node) {
if node != nil {
err := format.Node(&pkg.buf, pkg.fs, node)
var err error
if showSrc {
// Need an extra little dance to get internal comments to appear.
commentedNode := &printer.CommentedNode{
Node: node,
Comments: pkg.file.Comments,
}
err = format.Node(&pkg.buf, pkg.fs, commentedNode)
} else {
err = format.Node(&pkg.buf, pkg.fs, node)
}
if err != nil {
log.Fatal(err)
}
Expand Down

0 comments on commit e0a97a5

Please sign in to comment.