Skip to content

Commit

Permalink
gopls/internal/golang: improve extract variable edits
Browse files Browse the repository at this point in the history
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
  • Loading branch information
gayanper committed Mar 2, 2024
1 parent 283fce2 commit 4abfb1d
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions gopls/internal/golang/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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
}

Expand Down

0 comments on commit 4abfb1d

Please sign in to comment.