/*
* ====================================================================
* Copyright (c) 2005-2012 sventon project. All rights reserved.
*
* This software is licensed as described in the file LICENSE, which
* you should have received as part of this distribution. The terms
* are also available at http://www.sventon.org.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.sventon.diff;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Integer.parseInt;
import static org.sventon.model.DiffAction.parse;
/**
* Diff result parser.
*
* @author jesper@sventon.org
*/
final public class DiffResultParser {
/**
* Diff pattern.
* <p/>
* This pattern will match the following strings.
* <pre>
* 5c5
* 10d10
* 2,3d2
* 2d2,3
* 8a8,9
* 8,9a8
* 10,12c3,4
* </pre>
*/
private static final Pattern DIFF_PATTERN = Pattern.compile("^(\\d*),*(\\d*)([acd])(\\d*),*(\\d*)");
/**
* Private constructor.
*/
private DiffResultParser() {
}
/**
* Parses result generated by <code>QDiffNormalGenerator</code>.
*
* @param normalDiffResult The diff result.
* @return List of <code>DiffSegment</code>s.
*/
public static List<DiffSegment> parseNormalDiffResult(final String normalDiffResult) {
final List<DiffSegment> diffActions = new ArrayList<DiffSegment>();
final Scanner scanner = new Scanner(normalDiffResult);
try {
while (scanner.hasNextLine()) {
final Matcher matcher = DIFF_PATTERN.matcher(scanner.nextLine());
if (matcher.matches()) {
final int leftStart = parseInt(matcher.group(1));
final int leftEnd = "".equals(matcher.group(2)) ? parseInt(matcher.group(1)) : parseInt(matcher.group(2));
final int rightStart = parseInt(matcher.group(4));
final int rightEnd = "".equals(matcher.group(5)) ? parseInt(matcher.group(4)) : parseInt(matcher.group(5));
diffActions.add(new DiffSegment(parse(matcher.group(3)), leftStart, leftEnd, rightStart, rightEnd));
}
}
} finally {
scanner.close();
}
return diffActions;
}
}