Skip to content

Commit

Permalink
gencommon: fix comment detection on structs/interfaces (#50)
Browse files Browse the repository at this point in the history
### Background

#48

### Changes

- change the way we extract comments

### Testing

- updated tests
  • Loading branch information
drshriveer authored Dec 16, 2024
1 parent 5f905ef commit 315b52a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
24 changes: 23 additions & 1 deletion gencommon/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,31 @@ func CommentsFromObj(pkg *packages.Package, typeName string) Comments {
}

if decl, ok := obj.Decl.(*ast.TypeSpec); ok {
return FromCommentGroup(decl.Doc)
// structs/interfaces won't have comments built-in unless
// they're defined a particular way... e.g.
// type {
// // comment on MyType
// MyType struct {
// ...
// }
// }
// So we'll check that first, but then build a comment map and try to get the
// correct comment that way.
if decl.Doc != nil && len(decl.Doc.List) > 0 {
return FromCommentGroup(decl.Doc)
} else if decl.Comment != nil && len(decl.Comment.List) > 0 {
return FromCommentGroup(decl.Comment)
}
cmap := ast.NewCommentMap(pkg.Fset, stax, stax.Comments)
for tp, commentCommentGroups := range cmap {
if v, ok := tp.(*ast.GenDecl); ok && len(v.Specs) == 1 && v.Specs[0] == decl && len(commentCommentGroups) > 0 {
// take the LAST comment.... theoretically the closest comment to the actual struct we're looking at.
return FromCommentGroup(commentCommentGroups[len(commentCommentGroups)-1])
}
}
}
}

return nil
}

Expand Down
4 changes: 4 additions & 0 deletions gencommon/interface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ func TestFindInterface(t *testing.T) {
iface, err := gencommon.FindInterface(imports, pkgs, pkg.PkgPath, "TypeToGenerate", test.options)
require.NoError(t, err)

assert.Equal(t,
"// TypeToGenerate has a comment.\n// SecondLine of expected comment.",
iface.Comments.String())

expected := set.Make(test.expectedMethods...)
for _, m := range iface.Methods {
assert.Truef(t, expected.Remove(m.Name), "found duplicate OR unexpected method %q", m.Name)
Expand Down
4 changes: 4 additions & 0 deletions gencommon/internal/test_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import (
"github.com/drshriveer/gtools/gencommon/internal/nestedpkg"
)

// Comment to throw us off the trail.

// TypeToGenerate has a comment.
// SecondLine of expected comment.
type TypeToGenerate struct {
EmbeddedA
EmbeddedB
Expand Down

0 comments on commit 315b52a

Please sign in to comment.