org.eclipse.jgit.diff.EditList Java Examples

The following examples show how to use org.eclipse.jgit.diff.EditList. 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: 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 #2
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 #3
Source File: MyersAlgorithm.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public List<Comparison> compare(String source, String dest) {

  if ((source == null) || (dest == null)) {
    LOGGER.error("Source is {} and dest is {}", source, dest);
    throw new RuntimeException("Source and dest must not be null");
  }

  EditList diffList = new EditList();
  diffList.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT,
      new RawText(source.getBytes()), new RawText(dest.getBytes())));

  List<Comparison> comparisonList = new ArrayList<>();

  diffList.stream().forEachOrdered(edit -> {
    ComparisionType comparisionType;
    switch (edit.getType()) {
      case INSERT:
        comparisionType = ComparisionType.INSERT;
        break;
      case DELETE:
        comparisionType = ComparisionType.DELETE;
        break;
      case REPLACE:
        comparisionType = ComparisionType.REPLACE;
        break;
      default:
        comparisionType = ComparisionType.EQUAL;
        break;
    }
    comparisonList
        .add(new Comparison(comparisionType, edit.getBeginA(), edit.getEndA(), edit.getBeginB(), edit.getEndB()));
  });
  return comparisonList;
}
 
Example #4
Source File: CommitUtil.java    From SZZUnleashed with MIT License 5 votes vote down vote up
/**
 * Extract a list containing all Edits that exists between two revisions.
 *
 * @param entry a diffentry which contains information about a diff between two revisions.
 * @return an EditList containing all Edits.
 */
public EditList getDiffEditList(DiffEntry entry) throws IOException, GitAPIException {
  DiffFormatter form = new DiffFormatter(DisabledOutputStream.INSTANCE);
  form.setRepository(this.git.getRepository());

  FileHeader fh = form.toFileHeader(entry);
  return fh.toEditList();
}
 
Example #5
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 #6
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 #7
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 #8
Source File: ChangingIdentifiersRepositoryWalker.java    From naturalize with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void visitDiffEntry(final DiffEntry entry, final EditList editList,
		final RevCommit commit) throws IOException {
	final String sha = commit.name();
	if (entry.getNewPath().equals("/dev/null")) {
		currentStateOfIdentifiers.removeAll(entry.getOldPath()).forEach(
				i -> {
					if (!i.isDeleted()) {
						i.setIdentifierDeleted();
					}
				});
		return;
	}
	final String repositoryFolder = repository.getRepository()
			.getWorkTree() + "/";

	final File targetFile = new File(repositoryFolder + entry.getNewPath());
	final Set<IdentifierInformation> newIdentifierInfo = infoScanner
			.scanFile(targetFile, commit.name());
	if (currentStateOfIdentifiers.containsKey(entry.getOldPath())) {
		final Collection<IdentifierInformationThroughTime> state = currentStateOfIdentifiers
				.get(entry.getOldPath());
		final List<IdentifierInformationThroughTime> allIitts = Lists
				.newArrayList(state);
		final Set<IdentifierInformationThroughTime> setIitts = Sets
				.newIdentityHashSet();
		setIitts.addAll(state);
		checkArgument(setIitts.size() == allIitts.size(),
				"Before adding, state was inconsistent for ", targetFile);
		updateIdentifierInfoState(state, newIdentifierInfo, editList,
				entry.getNewPath());

		if (!entry.getOldPath().equals(entry.getNewPath())) {
			currentStateOfIdentifiers.putAll(entry.getNewPath(), state);
			currentStateOfIdentifiers.removeAll(entry.getOldPath());
		}
	} else {
		// This is a new file or a file we failed to index before, add
		// happily...
		// checkArgument(entry.getOldPath().equals("/dev/null"));
		final List<IdentifierInformationThroughTime> infosThroughTime = Lists
				.newArrayList();
		newIdentifierInfo
				.forEach(info -> {
					final IdentifierInformationThroughTime inf = new IdentifierInformationThroughTime();
					inf.addInformation(info);
					infosThroughTime.add(inf);
				});
		currentStateOfIdentifiers.putAll(entry.getNewPath(),
				infosThroughTime);
	}

}
 
Example #9
Source File: CommitUtil.java    From SZZUnleashed with MIT License 3 votes vote down vote up
/**
 * Extract filechanges between one revision and another. The resulting lines are formatted in a
 * git diff format. Each line starts with the line number separated with added or removerd
 * indicating if its the old or new file.
 *
 * @param newTree the new revision that contains the new changes.
 * @param oldTree the old revision that contains the old changes.
 * @param entry an DiffEntry that contains the number of changes between the newTree and the
 *     oldTree.
 * @return a list containing all diffing lines.
 */
public DiffLines diffFile(DiffEntry entry)
    throws IOException, GitAPIException {
  EditList edits = getDiffEditList(entry);

  DiffingLines differ = new DiffingLines(this.repo, this.customContext);

  return differ.getDiffingLines(entry, edits);
}
 
Example #10
Source File: JgitUtils.java    From contribution with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Default constructor.
 *
 * @param edits
 *            The list of base and patch line numbers with differences.
 * @param baseFileRaw
 *            The raw base file.
 * @param patchFileRaw
 *            The raw patch file.
 */
private JgitDifferenceIterator(EditList edits, RawText baseFileRaw, RawText patchFileRaw) {
    this.edits = edits;
    this.baseFileRaw = baseFileRaw;
    this.patchFileRaw = patchFileRaw;
}