1
0
mirror of https://github.com/golang/go synced 2024-11-19 00:44:40 -07:00
go/internal/lsp/diff/myers.go
Michael Matloob 27d1b4e4f3 internal/lsp/diff: rewrite ApplyEdits to work with sub-line diffs
This replaces the definition of ApplyEdits to be more like that in
go vet -fix, so that we can apply the results of suggested fixes.

Change-Id: Ib5724139464954e3790bc51ed1edc3ce4b2115ff
Reviewed-on: https://go-review.googlesource.com/c/tools/+/193959
Run-TryBot: Michael Matloob <matloob@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-09-09 18:07:23 +00:00

75 lines
1.8 KiB
Go

// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diff
import (
"fmt"
"strings"
"golang.org/x/tools/internal/lsp/diff/myers"
"golang.org/x/tools/internal/span"
)
func init() {
ComputeEdits = myersComputeEdits
ToUnified = myersToUnified
}
func myersComputeEdits(uri span.URI, before, after string) []TextEdit {
u := myers.SplitLines(before)
f := myers.SplitLines(after)
return myersDiffToEdits(uri, myers.Operations(u, f))
}
func myersToUnified(from, to string, before string, edits []TextEdit) string {
u := myers.SplitLines(before)
ops := myersEditsToDiff(edits)
return fmt.Sprint(myers.ToUnified(from, to, u, ops))
}
func myersDiffToEdits(uri span.URI, ops []*myers.Op) []TextEdit {
edits := make([]TextEdit, 0, len(ops))
for _, op := range ops {
s := span.New(uri, span.NewPoint(op.I1+1, 1, 0), span.NewPoint(op.I2+1, 1, 0))
switch op.Kind {
case myers.Delete:
// Delete: unformatted[i1:i2] is deleted.
edits = append(edits, TextEdit{Span: s})
case myers.Insert:
// Insert: formatted[j1:j2] is inserted at unformatted[i1:i1].
if content := strings.Join(op.Content, ""); content != "" {
edits = append(edits, TextEdit{Span: s, NewText: content})
}
}
}
return edits
}
func myersEditsToDiff(edits []TextEdit) []*myers.Op {
iToJ := 0
ops := make([]*myers.Op, len(edits))
for i, edit := range edits {
i1 := edit.Span.Start().Line() - 1
i2 := edit.Span.End().Line() - 1
kind := myers.Insert
if edit.NewText == "" {
kind = myers.Delete
}
ops[i] = &myers.Op{
Kind: kind,
Content: myers.SplitLines(edit.NewText),
I1: i1,
I2: i2,
J1: i1 + iToJ,
}
if kind == myers.Insert {
iToJ += len(ops[i].Content)
} else {
iToJ -= i2 - i1
}
}
return ops
}