MCPcopy Create free account
hub / github.com/sergi/go-diff / DiffFromDelta

Method DiffFromDelta

diffmatchpatch/diff.go:1278–1336  ·  view source on GitHub ↗

DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff.

(text1 string, delta string)

Source from the content-addressed store, hash-verified

1276
1277// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff.
1278func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) {
1279 i := 0
1280 runes := []rune(text1)
1281
1282 for _, token := range strings.Split(delta, "\t") {
1283 if len(token) == 0 {
1284 // Blank tokens are ok (from a trailing \t).
1285 continue
1286 }
1287
1288 // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality).
1289 param := token[1:]
1290
1291 switch op := token[0]; op {
1292 case '+':
1293 // Decode would Diff all "+" to " "
1294 param = strings.Replace(param, "+", "%2b", -1)
1295 param, err = url.QueryUnescape(param)
1296 if err != nil {
1297 return nil, err
1298 }
1299 if !utf8.ValidString(param) {
1300 return nil, fmt.Errorf("invalid UTF-8 token: %q", param)
1301 }
1302
1303 diffs = append(diffs, Diff{DiffInsert, param})
1304 case '=', '-':
1305 n, err := strconv.ParseInt(param, 10, 0)
1306 if err != nil {
1307 return nil, err
1308 } else if n < 0 {
1309 return nil, errors.New("Negative number in DiffFromDelta: " + param)
1310 }
1311
1312 i += int(n)
1313 // Break out if we are out of bounds, go1.6 can't handle this very well
1314 if i > len(runes) {
1315 break
1316 }
1317 // Remember that string slicing is by byte - we want by rune here.
1318 text := string(runes[i-int(n) : i])
1319
1320 if op == '=' {
1321 diffs = append(diffs, Diff{DiffEqual, text})
1322 } else {
1323 diffs = append(diffs, Diff{DiffDelete, text})
1324 }
1325 default:
1326 // Anything else is an error.
1327 return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0]))
1328 }
1329 }
1330
1331 if i != len(runes) {
1332 return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(runes))
1333 }
1334
1335 return diffs, nil

Callers 1

TestDiffDeltaFunction · 0.80

Calls

no outgoing calls

Tested by 1

TestDiffDeltaFunction · 0.64