org.eclipse.jgit.diff.Edit Java Examples

The following examples show how to use org.eclipse.jgit.diff.Edit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffLineFilter.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Only accept events that corresponding to the diff edits
 *
 * @return True if the event is corresponding to the diff edits
 */
@Override
public boolean accept(AuditEvent event) {
    List<Edit> editList = fileEditMap.get(event.getFileName());
    if (CollectionUtils.isEmpty(editList)) {
        return false;
    }
    for (Edit edit : editList) {
        if (edit.getBeginB() < event.getLine() && edit.getEndB() >= event.getLine()) {
            return true;
        }
        if (isEmptyLineSeparatorCheck(event) && event.getLine() == edit.getEndB() + 1) {
            return true;
        }
    }
    return false;
}
 
Example #2
Source File: ChangingIdentifiersRepositoryWalker.java    From naturalize with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a range of the possible line positions of the old line number in
 * the new file.
 *
 * @param declarationLineNumber
 * @param editList
 * @return
 */
private Range<Integer> getNewLineGivenOld(final int oldLineNumber,
		final EditList editList) {
	int offsetAbove = 0;
	for (final Edit edit : editList) {
		if (edit.getBeginA() < oldLineNumber
				&& edit.getEndA() < oldLineNumber) {
			offsetAbove += -(edit.getEndA() - edit.getBeginA())
					+ (edit.getEndB() - edit.getBeginB());
		} else if (edit.getBeginA() <= oldLineNumber
				&& edit.getEndA() >= oldLineNumber) {
			// if it was in the old range, it is now in the new range
			checkArgument(
					edit.getBeginA() + offsetAbove == edit.getBeginB(),
					"Beggining was %s but expected %s", edit.getBeginB(),
					edit.getBeginA() + offsetAbove);
			return Range.closed(edit.getBeginB(), edit.getEndB());
		} else {
			return Range.closed(oldLineNumber + offsetAbove, oldLineNumber
					+ offsetAbove);
		}
	}
	return Range.closed(oldLineNumber + offsetAbove, oldLineNumber
			+ offsetAbove);
}
 
Example #3
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
@Override
public Churn churn(Repository repository, RevCommit currentCommit) throws Exception {
	if (currentCommit.getParentCount() > 0) {
       	ObjectId oldTree = currentCommit.getParent(0).getTree();
        ObjectId newTree = currentCommit.getTree();
       	final TreeWalk tw = new TreeWalk(repository);
       	tw.setRecursive(true);
       	tw.addTree(oldTree);
       	tw.addTree(newTree);
       	
       	List<DiffEntry> diffs = DiffEntry.scan(tw);
       	DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
   		diffFormatter.setRepository(repository);
   		diffFormatter.setContext(0);
   		
       	int addedLines = 0;
   		int deletedLines = 0;
       	for (DiffEntry entry : diffs) {
   			FileHeader header = diffFormatter.toFileHeader(entry);
           	List<? extends HunkHeader> hunks = header.getHunks();
           	for (HunkHeader hunkHeader : hunks) {
           		for (Edit edit : hunkHeader.toEditList()) {
   					if (edit.getType() == Type.INSERT) {
   						addedLines += edit.getLengthB();
   					} else if (edit.getType() == Type.DELETE) {
   						deletedLines += edit.getLengthA();
   					} else if (edit.getType() == Type.REPLACE) {
   						deletedLines += edit.getLengthA();
   						addedLines += edit.getLengthB();
   					}
   				}
           	}
       	}
       	diffFormatter.close();
       	return new Churn(addedLines, deletedLines);
	}
	return null;
}
 
Example #4
Source File: DiffLineFilterTest.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testAccept() {
    String fileName = "test";
    int lineNum = 10;
    int beginB = 5;
    int endB = 12;

    AuditEvent event = PowerMockito.mock(AuditEvent.class);
    PowerMockito.doReturn(fileName).when(event).getFileName();
    PowerMockito.doReturn(lineNum).when(event).getLine();

    Edit edit = PowerMockito.mock(Edit.class);
    PowerMockito.doReturn(beginB).when(edit).getBeginB();
    PowerMockito.doReturn(endB).when(edit).getEndB();

    DiffEntryWrapper wrapper = PowerMockito.mock(DiffEntryWrapper.class);
    PowerMockito.doReturn(fileName).when(wrapper).getAbsoluteNewPath();
    PowerMockito.doReturn(Arrays.asList(edit)).when(wrapper).getEditList();

    DiffLineFilter filter = new DiffLineFilter(Arrays.asList(wrapper));

    Assert.assertTrue(filter.accept(event));
}
 
Example #5
Source File: DiffLineFilterTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testAcceptWithEmptyLineSeparator() {
    String fileName = "test";
    int lineNum = 10;
    int beginB = 5;
    int endB = 9;

    LocalizedMessage message = PowerMockito.mock(LocalizedMessage.class);
    PowerMockito.doReturn(EmptyLineSeparatorCheck.class.getName()).when(message).getSourceName();

    AuditEvent event = PowerMockito.mock(AuditEvent.class);
    PowerMockito.doReturn(fileName).when(event).getFileName();
    PowerMockito.doReturn(lineNum).when(event).getLine();
    PowerMockito.doReturn(message).when(event).getLocalizedMessage();

    Edit edit = PowerMockito.mock(Edit.class);
    PowerMockito.doReturn(beginB).when(edit).getBeginB();
    PowerMockito.doReturn(endB).when(edit).getEndB();

    DiffEntryWrapper wrapper = PowerMockito.mock(DiffEntryWrapper.class);
    PowerMockito.doReturn(fileName).when(wrapper).getAbsoluteNewPath();
    PowerMockito.doReturn(Arrays.asList(edit)).when(wrapper).getEditList();

    DiffLineFilter filter = new DiffLineFilter(Arrays.asList(wrapper));

    Assert.assertTrue(filter.accept(event));
}
 
Example #6
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<Edit> calculateEditList(RawText oldText, RawText newText) {
    EditList edits = diffAlgorithm.diff(comparator, oldText, newText);
    List<Edit> editList = new ArrayList<Edit>();
    for (Edit edit : edits) {
        editList.add(edit);
    }
    return editList;
}
 
Example #7
Source File: DiffEntryWrapperTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testIsAllDeletedEdits() {
    Edit edit1 = PowerMockito.mock(Edit.class);
    Edit edit2 = PowerMockito.mock(Edit.class);
    PowerMockito.when(edit1.getType()).thenReturn(Type.DELETE);
    PowerMockito.when(edit2.getType()).thenReturn(Type.DELETE);
    DiffEntryWrapper wrapper = DiffEntryWrapper.builder()
            .editList(Arrays.asList(edit1, edit2))
            .build();
    Assert.assertTrue(wrapper.isAllDeletedEdits());
}
 
Example #8
Source File: DiffCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testDoCalculateCommitDiffWhenFileAdded() throws Exception {
    try (Git git = new Git(db);
            ObjectReader reader = git.getRepository().newObjectReader()) {
        File repoDir = git.getRepository().getDirectory().getParentFile();
        File fileToAdd = new File(repoDir, "added.txt");
        File fileRemainUnchanged = new File(repoDir, "unchanged.txt");
        writeStringToFile(fileRemainUnchanged, "no change");
        git.add()
            .addFilepattern(fileRemainUnchanged.getName())
            .call();
        RevCommit oldCommit = doCommit(git);

        writeStringToFile(fileToAdd, "add file");
        git.add().addFilepattern(fileToAdd.getName()).call();
        RevCommit newCommit = doCommit(git);

        DiffCalculator calculator = DiffCalculator.builder()
                .diffAlgorithm(new HistogramDiff())
                .build();
        List<DiffEntryWrapper> wrappers = Whitebox.<List<DiffEntryWrapper>>invokeMethod(
                calculator, "doCalculateCommitDiff",
                oldCommit, newCommit, reader, git, repoDir, Collections.emptySet());

        Assert.assertEquals(1, wrappers.size());

        DiffEntryWrapper wrapper = wrappers.get(0);
        Assert.assertEquals(fileToAdd, wrapper.getNewFile());

        List<Edit> edits = wrapper.getEditList();

        Edit insertEdit = edits.get(0);
        Assert.assertEquals(Edit.Type.INSERT, insertEdit.getType());
        Assert.assertEquals(0, insertEdit.getBeginB());
        Assert.assertEquals(1, insertEdit.getEndB());

    }

}
 
Example #9
Source File: DiffCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testDoCalculateIndexedDiffWhenFileAdded() throws Exception {
    try (Git git = new Git(db);
            ObjectReader reader = git.getRepository().newObjectReader()) {
        File repoDir = git.getRepository().getDirectory().getParentFile();
        File fileToAdd = new File(repoDir, "added.txt");
        File fileRemainUnchanged = new File(repoDir, "unchanged.txt");
        writeStringToFile(fileRemainUnchanged, "no change");
        git.add()
            .addFilepattern(fileRemainUnchanged.getName())
            .call();
        RevCommit oldCommit = doCommit(git);

        writeStringToFile(fileToAdd, "add file");
        git.add().addFilepattern(fileToAdd.getName()).call();

        DiffCalculator calculator = DiffCalculator.builder()
                .diffAlgorithm(new HistogramDiff())
                .build();
        List<DiffEntryWrapper> wrappers = Whitebox.<List<DiffEntryWrapper>>invokeMethod(
                calculator, "doCalculateIndexedDiff",
                oldCommit, reader, git, repoDir);

        Assert.assertEquals(1, wrappers.size());

        DiffEntryWrapper wrapper = wrappers.get(0);
        Assert.assertEquals(fileToAdd, wrapper.getNewFile());

        List<Edit> edits = wrapper.getEditList();

        Edit insertEdit = edits.get(0);
        Assert.assertEquals(Edit.Type.INSERT, insertEdit.getType());
        Assert.assertEquals(0, insertEdit.getBeginB());
        Assert.assertEquals(1, insertEdit.getEndB());

    }

}
 
Example #10
Source File: HistogramDiff.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Override
public List<Change> computeDiff(List<T> source, List<T> target, DiffAlgorithmListener progress) {
    Objects.requireNonNull(source, "source list must not be null");
    Objects.requireNonNull(target, "target list must not be null");
    if (progress != null) {
        progress.diffStart();
    }
    EditList diffList = new EditList();
    diffList.addAll(new org.eclipse.jgit.diff.HistogramDiff().diff(new DataListComparator<>(progress), new DataList<>(source), new DataList<>(target)));
    List<Change> patch = new ArrayList<>();
    for (Edit edit : diffList) {
        DeltaType type = DeltaType.EQUAL;
        switch (edit.getType()) {
            case DELETE:
                type = DeltaType.DELETE;
                break;
            case INSERT:
                type = DeltaType.INSERT;
                break;
            case REPLACE:
                type = DeltaType.CHANGE;
                break;
        }
        patch.add(new Change(type, edit.getBeginA(), edit.getEndA(), edit.getBeginB(), edit.getEndB()));
    }
    if (progress != null) {
        progress.diffEnd();
    }
    return patch;
}
 
Example #11
Source File: DiffLineFilter.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean accept(RuleViolation violation) {
    List<Edit> editList = fileEditMap.get(violation.getFilename());
    if (editList == null || editList.isEmpty()) {
        return false;
    }
    for (Edit edit : editList) {
        if (edit.getBeginB() <= violation.getBeginLine() && edit.getEndB() >= violation.getEndLine()) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: DiffCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testCalculateDiff() throws Exception {
    try (Git git = new Git(db);
            ObjectReader reader = git.getRepository().newObjectReader()) {
        File repoDir = git.getRepository().getDirectory().getParentFile();
        File fileToChange = new File(repoDir, "changed.txt");
        File fileRemainUnchanged = new File(repoDir, "unchanged.txt");
        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line")
                .append("\n")
                .append("third line")
                .append("\n")
                .toString());
        writeStringToFile(fileRemainUnchanged, "no change");
        git.add()
            .addFilepattern(fileToChange.getName())
            .addFilepattern(fileRemainUnchanged.getName())
            .call();
        RevCommit oldCommit = doCommit(git);

        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line changed")
                .append("\n")
                .append("third line")
                .append("\n")
                .append("fourth line")
                .toString());
        git.add().addFilepattern(fileToChange.getName()).call();
        RevCommit newCommit = doCommit(git);

        DiffCalculator calculator = DiffCalculator.builder()
                .diffAlgorithm(new HistogramDiff())
                .comparator(RawTextComparator.DEFAULT)
                .bigFileThreshold(DiffHelper.DEFAULT_BIG_FILE_THRESHOLD)
                .build();
        List<DiffEntryWrapper> wrappers = calculator.calculateDiff(
                repoDir, oldCommit.name(), newCommit.name(), true);

        Assert.assertEquals(1, wrappers.size());

        DiffEntryWrapper wrapper = wrappers.get(0);
        Assert.assertEquals(fileToChange, wrapper.getNewFile());

        List<Edit> edits = wrapper.getEditList();

        Edit replaceEdit = edits.get(0);
        Assert.assertEquals(Edit.Type.REPLACE, replaceEdit.getType());
        Assert.assertEquals(1, replaceEdit.getBeginB());
        Assert.assertEquals(2, replaceEdit.getEndB());

        Edit insertEdit = edits.get(1);
        Assert.assertEquals(Edit.Type.INSERT, insertEdit.getType());
        Assert.assertEquals(3, insertEdit.getBeginB());
        Assert.assertEquals(4, insertEdit.getEndB());
    }

}
 
Example #13
Source File: DiffCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testDoCalculateCommitDiffWhenFileChanged() throws Exception {
    try (Git git = new Git(db);
            ObjectReader reader = git.getRepository().newObjectReader()) {
        File repoDir = git.getRepository().getDirectory().getParentFile();
        File fileToChange = new File(repoDir, "changed.txt");
        File fileRemainUnchanged = new File(repoDir, "unchanged.txt");
        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line")
                .append("\n")
                .append("third line")
                .append("\n")
                .toString());
        writeStringToFile(fileRemainUnchanged, "no change");
        git.add()
            .addFilepattern(fileToChange.getName())
            .addFilepattern(fileRemainUnchanged.getName())
            .call();
        RevCommit oldCommit = doCommit(git);

        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line changed")
                .append("\n")
                .append("third line")
                .append("\n")
                .append("fourth line")
                .toString());
        git.add().addFilepattern(fileToChange.getName()).call();
        RevCommit newCommit = doCommit(git);

        DiffCalculator calculator = DiffCalculator.builder()
                .diffAlgorithm(new HistogramDiff())
                .build();
        List<DiffEntryWrapper> wrappers = Whitebox.<List<DiffEntryWrapper>>invokeMethod(
                calculator, "doCalculateCommitDiff",
                oldCommit, newCommit, reader, git, repoDir, Collections.emptySet());

        Assert.assertEquals(1, wrappers.size());

        DiffEntryWrapper wrapper = wrappers.get(0);
        Assert.assertEquals(fileToChange, wrapper.getNewFile());

        List<Edit> edits = wrapper.getEditList();

        Edit replaceEdit = edits.get(0);
        Assert.assertEquals(Edit.Type.REPLACE, replaceEdit.getType());
        Assert.assertEquals(1, replaceEdit.getBeginB());
        Assert.assertEquals(2, replaceEdit.getEndB());

        Edit insertEdit = edits.get(1);
        Assert.assertEquals(Edit.Type.INSERT, insertEdit.getType());
        Assert.assertEquals(3, insertEdit.getBeginB());
        Assert.assertEquals(4, insertEdit.getEndB());
    }

}
 
Example #14
Source File: DiffCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testDoCalculateIndexedDiffWhenFileChanged() throws Exception {
    try (Git git = new Git(db);
            ObjectReader reader = git.getRepository().newObjectReader()) {
        File repoDir = git.getRepository().getDirectory().getParentFile();
        File fileToChange = new File(repoDir, "changed.txt");
        File fileRemainUnchanged = new File(repoDir, "unchanged.txt");
        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line")
                .append("\n")
                .append("third line")
                .append("\n")
                .toString());
        writeStringToFile(fileRemainUnchanged, "no change");
        git.add()
            .addFilepattern(fileToChange.getName())
            .addFilepattern(fileRemainUnchanged.getName())
            .call();
        RevCommit oldCommit = doCommit(git);

        writeStringToFile(fileToChange, new StringBuilder()
                .append("first line")
                .append("\n")
                .append("second line changed")
                .append("\n")
                .append("third line")
                .append("\n")
                .append("fourth line")
                .toString());
        git.add().addFilepattern(fileToChange.getName()).call();

        DiffCalculator calculator = DiffCalculator.builder()
                .diffAlgorithm(new HistogramDiff())
                .build();
        List<DiffEntryWrapper> wrappers = Whitebox.<List<DiffEntryWrapper>>invokeMethod(
                calculator, "doCalculateIndexedDiff",
                oldCommit, reader, git, repoDir);

        Assert.assertEquals(1, wrappers.size());

        DiffEntryWrapper wrapper = wrappers.get(0);
        Assert.assertEquals(fileToChange, wrapper.getNewFile());

        List<Edit> edits = wrapper.getEditList();

        Edit replaceEdit = edits.get(0);
        Assert.assertEquals(Edit.Type.REPLACE, replaceEdit.getType());
        Assert.assertEquals(1, replaceEdit.getBeginB());
        Assert.assertEquals(2, replaceEdit.getEndB());

        Edit insertEdit = edits.get(1);
        Assert.assertEquals(Edit.Type.INSERT, insertEdit.getType());
        Assert.assertEquals(3, insertEdit.getBeginB());
        Assert.assertEquals(4, insertEdit.getEndB());
    }

}
 
Example #15
Source File: DiffingLines.java    From SZZUnleashed with MIT License 4 votes vote down vote up
/**
 * Get the formatted diff between two commits.
 *
 * @param entry the DiffEntry object containing the real diff.
 * @param edits the edited chunks.
 * @return the Diffing lines with line numbers.
 */
public DiffLines getDiffingLines(DiffEntry entry, EditList edits) throws IOException, GitAPIException {
  /*
   * Access the RawText objects for the old and the new entry.
   */
  RawText old = toRaw(entry.getOldId());
  RawText present = toRaw(entry.getNewId());

  /*
   * If the old file is null, it indicates that a new file has been made.
   */
  if (old == null || present == null) return new DiffLines();

  DiffLines lines = new DiffLines();

  int i = 0;
  /*
   * Loop through all edits.
   */
  while (i < edits.size()) {
      Edit first = edits.get(i);
      int last = last(edits, i);
      Edit second = edits.get(last);

      /*
       * Get the limits for the change in the old file.
       */
      int firstIndex = first.getBeginA() - customContext;
      int firstEnd = second.getEndA() + customContext;

      /*
       * Get the limits for the change in the new file.
       */
      int secondIndex = first.getBeginB() - customContext;
      int secondEnd = second.getEndB() + customContext;

      /*
       * Are they out of boundary?
       */
      firstIndex = 0 > firstIndex ? 0 : firstIndex;
      firstEnd = old.size() < firstEnd ? old.size() : firstEnd;

      secondIndex = 0 > secondIndex ? 0 : secondIndex;
      secondEnd = present.size() < secondEnd ? present.size() : secondEnd;

      /*
       * Loop through both revisions parallel.
       */
      while (firstIndex < firstEnd || secondIndex < secondEnd) {
          String[] info = null;

          if (firstIndex < first.getBeginA() || last + 1 < i) {
              if (this.omitLineText) {
                info = new String[]{Integer.toString(firstIndex), Integer.toString(firstIndex)};
              } else {
                info = new String[]{Integer.toString(firstIndex), old.getString(firstIndex)};
              }
              lines.insertions.add(info);
              
              firstIndex+=1;
              secondIndex+=1;
          } else if (firstIndex < first.getEndA()) {
              if (this.omitLineText) {
                info = new String[]{Integer.toString(firstIndex), Integer.toString(firstIndex)};
              } else {
                info = new String[]{Integer.toString(firstIndex), old.getString(firstIndex)};
              }
              lines.deletions.add(info);
              firstIndex+=1;
          } else if (secondIndex < first.getEndB()) {
              if (this.omitLineText) {
                info = new String[]{Integer.toString(secondIndex), Integer.toString(secondIndex)};
              } else {
                info = new String[]{Integer.toString(secondIndex), present.getString(secondIndex)};
              }
              lines.insertions.add(info);
              secondIndex+=1;
          }

          /*
           * Check if there is a gap between the next diff.
           */
          if (firstIndex >= first.getEndA() &&
              secondIndex >= first.getEndB() &&
              ++i < edits.size()){
              first = edits.get(i);
          }
      }
  }
  return lines;
}
 
Example #16
Source File: MergeAlgorithm.java    From onedev with MIT License 4 votes vote down vote up
private static boolean isEndEdit(Edit edit) {
	return edit == END_EDIT;
}
 
Example #17
Source File: GitHelper.java    From repairnator with MIT License 4 votes vote down vote up
public void computePatchStats(JobStatus jobStatus, Git git, RevCommit headRev, RevCommit commit) {
    try {
        ObjectReader reader = git.getRepository().newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, headRev.getTree());
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, commit.getTree());

        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(git.getRepository());
        diffFormatter.setContext(0);
        List<DiffEntry> entries = diffFormatter.scan(newTreeIter, oldTreeIter);

        int nbLineAdded = 0;
        int nbLineDeleted = 0;
        Set<String> changedFiles = new HashSet<>();
        Set<String> addedFiles = new HashSet<>();
        Set<String> deletedFiles = new HashSet<>();

        for (DiffEntry entry : entries) {
            String path;
            if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                path = entry.getOldPath();
            } else {
                path = entry.getNewPath();
            }
            if (!jobStatus.isCreatedFileToPush(path) && path.endsWith(".java")) {
                if (entry.getChangeType() == DiffEntry.ChangeType.MODIFY ||
                        entry.getChangeType() == DiffEntry.ChangeType.RENAME) {
                    changedFiles.add(path);
                } else if (entry.getChangeType() == DiffEntry.ChangeType.ADD ||
                        entry.getChangeType() == DiffEntry.ChangeType.COPY) {
                    addedFiles.add(path);
                } else if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                    deletedFiles.add(path);
                }

                FileHeader fileHeader = diffFormatter.toFileHeader(entry);
                List<? extends HunkHeader> hunks = fileHeader.getHunks();
                for (HunkHeader hunk : hunks) {
                    EditList edits = hunk.toEditList();
                    for (Edit edit : edits) {
                        switch (edit.getType()) {
                            case INSERT:
                                nbLineAdded += edit.getLengthB();
                                break;

                            case DELETE:
                                nbLineDeleted += edit.getLengthA();
                                break;

                            case REPLACE:
                                int diff = edit.getLengthA() - edit.getLengthB();
                                if (diff > 0) {
                                    nbLineAdded += edit.getLengthA();
                                    nbLineDeleted += edit.getLengthB();
                                } else {
                                    nbLineDeleted += edit.getLengthA();
                                    nbLineAdded += edit.getLengthB();
                                }
                                break;

                            case EMPTY:
                                break;
                        }
                    }
                }
            }
        }

        PatchDiff patchDiff = jobStatus.getProperties().getPatchDiff();
        patchDiff.getFiles().setNumberAdded(addedFiles.size());
        patchDiff.getFiles().setNumberChanged(changedFiles.size());
        patchDiff.getFiles().setNumberDeleted(deletedFiles.size());
        patchDiff.getLines().setNumberAdded(nbLineAdded);
        patchDiff.getLines().setNumberDeleted(nbLineDeleted);
    } catch (IOException e) {
        this.getLogger().error("Error while computing stat on the patch.", e);
    }
}
 
Example #18
Source File: MergeAlgorithm.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Helper method which returns the next Edit for an Iterator over Edits.
 * When there are no more edits left this method will return the constant
 * END_EDIT.
 *
 * @param it
 *            the iterator for which the next edit should be returned
 * @return the next edit from the iterator or END_EDIT if there no more
 *         edits
 */
private static Edit nextEdit(Iterator<Edit> it) {
	return (it.hasNext() ? it.next() : END_EDIT);
}