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