Skip to content

Commit

Permalink
internal/lsp: add fields to anonymous struct info
Browse files Browse the repository at this point in the history
Anonymous struct quick fixes should provide more information on
which struct they will fill. This adds the first fields of an
anonymous struct to the fill title.

Updates golang/go#48563

Change-Id: I42cee2e8b1b9405ac2e2e8cfb8deb2c7710c3056
Reviewed-on: https://go-review.googlesource.com/c/tools/+/351591
Trust: Suzy Mueller <[email protected]>
Run-TryBot: Suzy Mueller <[email protected]>
gopls-CI: kokoro <[email protected]>
TryBot-Result: Go Bot <[email protected]>
Reviewed-by: Rebecca Stambler <[email protected]>
  • Loading branch information
suzmue committed Sep 24, 2021
1 parent 939195f commit ba6b94c
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion internal/lsp/analysis/fillstruct/fillstruct.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"go/format"
"go/token"
"go/types"
"strings"
"unicode"

"golang.org/x/tools/go/analysis"
Expand Down Expand Up @@ -87,13 +88,15 @@ func run(pass *analysis.Pass) (interface{}, error) {
}

var fillable bool
var fillableFields []string
for i := 0; i < fieldCount; i++ {
field := obj.Field(i)
// Ignore fields that are not accessible in the current package.
if field.Pkg() != nil && field.Pkg() != pass.Pkg && !field.Exported() {
continue
}
fillable = true
fillableFields = append(fillableFields, fmt.Sprintf("%s: %s", field.Name(), field.Type().String()))
}
if !fillable {
return
Expand All @@ -105,7 +108,21 @@ func run(pass *analysis.Pass) (interface{}, error) {
case *ast.SelectorExpr:
name = fmt.Sprintf("%s.%s", typ.X, typ.Sel.Name)
default:
name = "anonymous struct"
totalFields := len(fillableFields)
maxLen := 20
// Find the index to cut off printing of fields.
var i, fieldLen int
for i = range fillableFields {
if fieldLen > maxLen {
break
}
fieldLen += len(fillableFields[i])
}
fillableFields = fillableFields[:i]
if i < totalFields {
fillableFields = append(fillableFields, "...")
}
name = fmt.Sprintf("anonymous struct { %s }", strings.Join(fillableFields, ", "))
}
pass.Report(analysis.Diagnostic{
Message: fmt.Sprintf("Fill %s", name),
Expand Down

0 comments on commit ba6b94c

Please sign in to comment.