|
| 1 | +package se.bjurr.violations.lib.parsers; |
| 2 | + |
| 3 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 4 | +import static java.util.stream.Collectors.joining; |
| 5 | +import static se.bjurr.violations.lib.model.Violation.violationBuilder; |
| 6 | +import static se.bjurr.violations.lib.reports.Parser.DIFF; |
| 7 | + |
| 8 | +import java.io.ByteArrayInputStream; |
| 9 | +import java.io.InputStream; |
| 10 | +import java.util.Set; |
| 11 | +import java.util.TreeSet; |
| 12 | + |
| 13 | +import com.github.difflib.patch.AbstractDelta; |
| 14 | +import com.github.difflib.patch.ChangeDelta; |
| 15 | +import com.github.difflib.patch.DeltaType; |
| 16 | +import com.github.difflib.patch.Patch; |
| 17 | +import com.github.difflib.unifieddiff.UnifiedDiff; |
| 18 | +import com.github.difflib.unifieddiff.UnifiedDiffFile; |
| 19 | +import com.github.difflib.unifieddiff.UnifiedDiffReader; |
| 20 | + |
| 21 | +import se.bjurr.violations.lib.ViolationsLogger; |
| 22 | +import se.bjurr.violations.lib.model.SEVERITY; |
| 23 | +import se.bjurr.violations.lib.model.Violation; |
| 24 | + |
| 25 | +public class DiffParser implements ViolationsParser { |
| 26 | + |
| 27 | + @Override |
| 28 | + public Set<Violation> parseReportOutput(String reportContent, ViolationsLogger violationsLogger) throws Exception { |
| 29 | + Set<Violation> violations = new TreeSet<>(); |
| 30 | + InputStream reportContentStream = new ByteArrayInputStream(reportContent.getBytes(UTF_8)); |
| 31 | + UnifiedDiff parsedDiff = UnifiedDiffReader.parseUnifiedDiff(reportContentStream); |
| 32 | + for(UnifiedDiffFile diffFile : parsedDiff.getFiles()) { |
| 33 | + String file = diffFile.getFromFile(); |
| 34 | + Patch<String> patch = diffFile.getPatch(); |
| 35 | + for (AbstractDelta<?> delta : patch.getDeltas()) { |
| 36 | + if (delta.getType() == DeltaType.CHANGE) { |
| 37 | + @SuppressWarnings("unchecked") |
| 38 | + ChangeDelta<String> changeDelta = (ChangeDelta<String>)delta; |
| 39 | + String fromString = changeDelta.getSource().getLines().stream().collect(joining("\n")); |
| 40 | + int fromLine = changeDelta.getSource().getPosition(); |
| 41 | + String toString = changeDelta.getTarget().getLines().stream().collect(joining("\n")); |
| 42 | + changeDelta.getTarget().getPosition(); |
| 43 | + |
| 44 | + violations.add(violationBuilder() |
| 45 | + .setParser(DIFF) |
| 46 | + .setFile(file) |
| 47 | + .setStartLine(fromLine) |
| 48 | + .setMessage(fromString+"\n\nTo:\n\n"+toString) |
| 49 | + .setSeverity(SEVERITY.ERROR) |
| 50 | + .build()); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return violations; |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments