Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 19 additions & 19 deletions diffmatchpatch/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package diffmatchpatch
import (
"bytes"
"errors"
"fmt"
"math"
"net/url"
"regexp"
Expand All @@ -31,26 +32,8 @@ type Patch struct {
// Header: @@ -382,8 +481,9 @@
// Indices are printed as 1-based, not 0-based.
func (p *Patch) String() string {
var coords1, coords2 string

if p.Length1 == 0 {
coords1 = strconv.Itoa(p.Start1) + ",0"
} else if p.Length1 == 1 {
coords1 = strconv.Itoa(p.Start1 + 1)
} else {
coords1 = strconv.Itoa(p.Start1+1) + "," + strconv.Itoa(p.Length1)
}

if p.Length2 == 0 {
coords2 = strconv.Itoa(p.Start2) + ",0"
} else if p.Length2 == 1 {
coords2 = strconv.Itoa(p.Start2 + 1)
} else {
coords2 = strconv.Itoa(p.Start2+1) + "," + strconv.Itoa(p.Length2)
}

var text bytes.Buffer
_, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n")
_, _ = text.WriteString(p.header())

// Escape the body of the patch with %xx notation.
for _, aDiff := range p.diffs {
Expand All @@ -70,6 +53,23 @@ func (p *Patch) String() string {
return unescaper.Replace(text.String())
}

func (p Patch) header() string {
return fmt.Sprintf("@@ -%s +%s @@\n",
p.coords(p.Start1, p.Length1),
p.coords(p.Start2, p.Length2))
}

func (Patch) coords(start, length int) string {
switch {
case length == 0:
return fmt.Sprintf("%d,0", start)
case length == 1:
return fmt.Sprintf("%d", start+1)
default:
return fmt.Sprintf("%d,%d", start+1, length)
}
}

// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits.
func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch {
if len(text) == 0 {
Expand Down
Loading