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

Function ApplyPatch

internal/diff/diff.go:39–69  ·  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 (BUG-3839). go-diff up to 1.4.0 could panic or return invalid UTF-8 even on valid text when applying a patch over another

(baseText, patchText string)

Source from the content-addressed store, hash-verified

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

Calls 2

patchTextValidUTF8Function · 0.85
patchApplyFunction · 0.85