MCPcopy Create free account
hub / github.com/PerpetualSoftware/pad / ApplyPatch

Function ApplyPatch

internal/diff/diff.go:38–68  ·  view source on GitHub ↗

ApplyPatch applies a patch to baseText to produce the target text. Returns an error if the patch cannot be applied cleanly, or if the base or the patch's text is not valid UTF-8: go-diff slices such text at offsets it derives from runes, and panics or builds the wrong text (BUG-3839). go-diff also

(baseText, patchText string)

Source from the content-addressed store, hash-verified

36// An empty patch returns baseText as it is, valid or not: it records a
37// version byte-identical to its base, and go-diff is never reached.
38func ApplyPatch(baseText, patchText string) (string, error) {
39 if patchText == "" {
40 return baseText, nil
41 }
42 if !utf8.ValidString(baseText) {
43 return "", fmt.Errorf("base text is not valid UTF-8")
44 }
45 if !patchTextValidUTF8(patchText) {
46 return "", fmt.Errorf("patch text is not valid UTF-8")
47 }
48 patches, err := dmp.PatchFromText(patchText)
49 if err != nil {
50 return "", fmt.Errorf("parse patch: %w", err)
51 }
52 result, applied, err := patchApply(patches, baseText)
53 if err != nil {
54 return "", err
55 }
56 // Check that all hunks applied
57 for i, ok := range applied {
58 if !ok {
59 return "", fmt.Errorf("patch hunk %d failed to apply", i)
60 }
61 }
62 // Over a base it was not made from, go-diff can also succeed and cut a
63 // rune in half: valid text in, invalid text out. No version recorded that.
64 if !utf8.ValidString(result) {
65 return "", fmt.Errorf("applying the patch produced text that is not valid UTF-8")
66 }
67 return result, nil
68}
69
70// patchTextValidUTF8 reports whether every text line of a patch decodes to
71// valid UTF-8. A line is escaped, so "%FF" is the byte 0xFF once parsed; this

Calls 2

patchTextValidUTF8Function · 0.85
patchApplyFunction · 0.85