Skip to content

Commit

Permalink
gopls/diff/unified: remove redundant information
Browse files Browse the repository at this point in the history
Sometimes the unified diff would show the same line removed and added.
That is avoided by this CL.

Fixes: golang/go#59232

Change-Id: Ie6562e3c922b8f0c4319eefdde1913b2d9bc7878
Reviewed-on: https://go-review.googlesource.com/c/tools/+/489695
Run-TryBot: Peter Weinberger <pjw@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
  • Loading branch information
pjweinbgo committed May 8, 2023
1 parent 479f5c6 commit 3d99ebe
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
4 changes: 2 additions & 2 deletions internal/diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ func lineEdits(src string, edits []Edit) ([]Edit, error) {
}

// Do all edits begin and end at the start of a line?
// TODO(adonovan): opt: is this fast path necessary?
// (Also, it complicates the result ownership.)
// TODO(adonovan, pjw): why does omitting this 'optimization'
// cause tests to fail? (TestDiff/insert-line,extra_newline)
for _, edit := range edits {
if edit.Start >= len(src) || // insertion at EOF
edit.Start > 0 && src[edit.Start-1] != '\n' || // not at line start
Expand Down
7 changes: 7 additions & 0 deletions internal/diff/difftest/difftest.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,13 @@ var TestCases = []struct {
-
A
`,
}, {
Name: "unified_lines",
In: "aaa\nccc\n",
Out: "aaa\nbbb\nccc\n",
Edits: []diff.Edit{{Start: 3, End: 3, New: "\nbbb"}},
LineEdits: []diff.Edit{{Start: 0, End: 4, New: "aaa\nbbb\n"}},
Unified: UnifiedPrefix + "@@ -1,2 +1,3 @@\n aaa\n+bbb\n ccc\n",
},
}

Expand Down
13 changes: 11 additions & 2 deletions internal/diff/unified.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,18 @@ func toUnified(fromName, toName string, content string, edits []Edit) (unified,
last++
}
if edit.New != "" {
for _, content := range splitLines(edit.New) {
h.Lines = append(h.Lines, line{Kind: Insert, Content: content})
for i, content := range splitLines(edit.New) {
toLine++
// Merge identical Delete+Insert.
// This is an unwanted output of converting diffs to line diffs
// that is easiest to fix by postprocessing.
// e.g. issue #59232: ("aaa\nccc\n", "aaa\nbbb\nccc")
// -> [Delete "aaa\n", Insert "aaa\n", Insert "bbb\n", ...].
if i == 0 && last > start && h.Lines[len(h.Lines)-1].Content == content {
h.Lines[len(h.Lines)-1].Kind = Equal
continue
}
h.Lines = append(h.Lines, line{Kind: Insert, Content: content})
}
}
}
Expand Down

0 comments on commit 3d99ebe

Please sign in to comment.