From ba6b94c735d2f7b74804e255e653a4292074ae76 Mon Sep 17 00:00:00 2001 From: Suzy Mueller Date: Wed, 22 Sep 2021 16:28:20 -0600 Subject: [PATCH] internal/lsp: add fields to anonymous struct info 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 Run-TryBot: Suzy Mueller gopls-CI: kokoro TryBot-Result: Go Bot Reviewed-by: Rebecca Stambler --- .../lsp/analysis/fillstruct/fillstruct.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/internal/lsp/analysis/fillstruct/fillstruct.go b/internal/lsp/analysis/fillstruct/fillstruct.go index 36a63a1f6e..05472888b6 100644 --- a/internal/lsp/analysis/fillstruct/fillstruct.go +++ b/internal/lsp/analysis/fillstruct/fillstruct.go @@ -13,6 +13,7 @@ import ( "go/format" "go/token" "go/types" + "strings" "unicode" "golang.org/x/tools/go/analysis" @@ -87,6 +88,7 @@ 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. @@ -94,6 +96,7 @@ func run(pass *analysis.Pass) (interface{}, error) { continue } fillable = true + fillableFields = append(fillableFields, fmt.Sprintf("%s: %s", field.Name(), field.Type().String())) } if !fillable { return @@ -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),