2019-06-20 14:57:45 -06:00
|
|
|
package source
|
|
|
|
|
2019-08-08 13:30:52 -06:00
|
|
|
import (
|
2019-09-06 12:55:14 -06:00
|
|
|
"context"
|
2019-08-19 17:28:08 -06:00
|
|
|
|
2019-08-08 13:30:52 -06:00
|
|
|
"golang.org/x/tools/go/analysis"
|
2019-09-06 12:55:14 -06:00
|
|
|
"golang.org/x/tools/internal/lsp/protocol"
|
2019-09-16 16:17:51 -06:00
|
|
|
"golang.org/x/tools/internal/span"
|
2019-08-08 13:30:52 -06:00
|
|
|
)
|
2019-06-20 14:57:45 -06:00
|
|
|
|
2019-09-24 14:28:59 -06:00
|
|
|
type SuggestedFix struct {
|
|
|
|
Title string
|
|
|
|
Edits map[span.URI][]protocol.TextEdit
|
|
|
|
}
|
|
|
|
|
2019-10-04 15:18:43 -06:00
|
|
|
func suggestedFixes(ctx context.Context, view View, pkg Package, diag *analysis.Diagnostic) ([]SuggestedFix, error) {
|
2019-09-06 12:55:14 -06:00
|
|
|
var fixes []SuggestedFix
|
2019-08-08 13:30:52 -06:00
|
|
|
for _, fix := range diag.SuggestedFixes {
|
2019-09-24 14:28:59 -06:00
|
|
|
edits := make(map[span.URI][]protocol.TextEdit)
|
2019-09-06 12:55:14 -06:00
|
|
|
for _, e := range fix.TextEdits {
|
2019-09-16 16:17:51 -06:00
|
|
|
posn := view.Session().Cache().FileSet().Position(e.Pos)
|
2019-09-24 14:28:59 -06:00
|
|
|
uri := span.FileURI(posn.Filename)
|
|
|
|
ph, _, err := pkg.FindFile(ctx, uri)
|
2019-09-16 16:17:51 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-09-17 09:19:11 -06:00
|
|
|
_, m, _, err := ph.Cached(ctx)
|
|
|
|
if err != nil {
|
2019-09-16 16:17:51 -06:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
mrng, err := posToRange(ctx, view, m, e.Pos, e.End)
|
2019-08-08 13:30:52 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-09-06 12:55:14 -06:00
|
|
|
rng, err := mrng.Range()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-09-24 14:28:59 -06:00
|
|
|
edits[uri] = append(edits[uri], protocol.TextEdit{
|
2019-09-06 12:55:14 -06:00
|
|
|
Range: rng,
|
|
|
|
NewText: string(e.NewText),
|
|
|
|
})
|
2019-08-08 13:30:52 -06:00
|
|
|
}
|
2019-09-06 12:55:14 -06:00
|
|
|
fixes = append(fixes, SuggestedFix{
|
|
|
|
Title: fix.Message,
|
|
|
|
Edits: edits,
|
|
|
|
})
|
2019-08-08 13:30:52 -06:00
|
|
|
}
|
2019-09-06 12:55:14 -06:00
|
|
|
return fixes, nil
|
2019-06-20 14:57:45 -06:00
|
|
|
}
|
2019-09-24 14:28:59 -06:00
|
|
|
|
|
|
|
// onlyDeletions returns true if all of the suggested fixes are deletions.
|
|
|
|
func onlyDeletions(fixes []SuggestedFix) bool {
|
|
|
|
for _, fix := range fixes {
|
|
|
|
for _, edits := range fix.Edits {
|
|
|
|
for _, edit := range edits {
|
|
|
|
if edit.NewText != "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|