Skip to content

Commit 4abfb1d

Browse files
committed
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 #65944
1 parent 283fce2 commit 4abfb1d

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

gopls/internal/golang/extract.go

+18-4
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,12 @@ func extractVariable(fset *token.FileSet, start, end token.Pos, src []byte, file
7878
if err := format.Node(&buf, fset, assignStmt); err != nil {
7979
return nil, nil, err
8080
}
81-
assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent
81+
var edits []analysis.TextEdit
8282

83-
return fset, &analysis.SuggestedFix{
84-
TextEdits: []analysis.TextEdit{
83+
switch insertBeforeStmt := insertBeforeStmt.(type) {
84+
case *ast.DeclStmt, *ast.AssignStmt:
85+
assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent
86+
edits = []analysis.TextEdit{
8587
{
8688
Pos: insertBeforeStmt.Pos(),
8789
End: insertBeforeStmt.Pos(),
@@ -92,7 +94,19 @@ func extractVariable(fset *token.FileSet, start, end token.Pos, src []byte, file
9294
End: end,
9395
NewText: []byte(lhs),
9496
},
95-
},
97+
}
98+
default:
99+
assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent)
100+
edits = []analysis.TextEdit{
101+
{
102+
Pos: start,
103+
End: end,
104+
NewText: []byte(assignment),
105+
},
106+
}
107+
}
108+
return fset, &analysis.SuggestedFix{
109+
TextEdits: edits,
96110
}, nil
97111
}
98112

0 commit comments

Comments
 (0)