From ebc1a8b5663f8f2e2c5ba416fe5c5c616a835c73 Mon Sep 17 00:00:00 2001 From: Gayan Perera Date: Sat, 2 Mar 2024 10:33:08 +0100 Subject: [PATCH] gopls/internal/golang: improve extract variable edits The previous implementation use common edits to support both scenarios where a assignment/declaration exist and did not exist. This cause a additional text edit with lhs values in the new line when the extraction was done on a expression which was not part of a assignment/declaration. The new changes address this scenarios by computing edits based on the scenario to avoid the additional lhs in new line when extracted expression is not part of a assignment/declaration. Fixes golang/tools#65944 --- gopls/internal/golang/extract.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/gopls/internal/golang/extract.go b/gopls/internal/golang/extract.go index c07faec1b7a..8903538e02d 100644 --- a/gopls/internal/golang/extract.go +++ b/gopls/internal/golang/extract.go @@ -78,10 +78,12 @@ func extractVariable(fset *token.FileSet, start, end token.Pos, src []byte, file if err := format.Node(&buf, fset, assignStmt); err != nil { return nil, nil, err } - assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent + var edits []analysis.TextEdit - return fset, &analysis.SuggestedFix{ - TextEdits: []analysis.TextEdit{ + switch insertBeforeStmt := insertBeforeStmt.(type) { + case *ast.DeclStmt, *ast.AssignStmt: + assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent + edits = []analysis.TextEdit{ { Pos: insertBeforeStmt.Pos(), End: insertBeforeStmt.Pos(), @@ -92,7 +94,19 @@ func extractVariable(fset *token.FileSet, start, end token.Pos, src []byte, file End: end, NewText: []byte(lhs), }, - }, + } + default: + assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + edits = []analysis.TextEdit{ + { + Pos: start, + End: end, + NewText: []byte(assignment), + }, + } + } + return fset, &analysis.SuggestedFix{ + TextEdits: edits, }, nil }