org.eclipse.jgit.diff.RawTextComparator Java Examples

The following examples show how to use org.eclipse.jgit.diff.RawTextComparator. 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: GitCommit.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException {
	RevWalk revWalk = new RevWalk(repository);
	parent = revWalk.parseCommit(parent.getId());
	revWalk.close();
	ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE);
	DiffFormatter df = new DiffFormatter(put);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);
	List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
	for(DiffEntry e : diffs){
		df.format(e);
		String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable
		returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType()));
		put.reset();
	}
	df.close();
}
 
Example #2
Source File: ResolveMerger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Does the content merge. The three texts base, ours and theirs are
 * specified with {@link CanonicalTreeParser}. If any of the parsers is
 * specified as <code>null</code> then an empty text will be used instead.
 *
 * @param base
 * @param ours
 * @param theirs
 * @param attributes
 *
 * @return the result of the content merge
 * @throws IOException
 */
private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
		CanonicalTreeParser ours, CanonicalTreeParser theirs,
		Attributes attributes)
		throws IOException {
	RawText baseText;
	RawText ourText;
	RawText theirsText;

	try {
		baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
						base.getEntryObjectId(), attributes);
		ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
						ours.getEntryObjectId(), attributes);
		theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
						theirs.getEntryObjectId(), attributes);
	} catch (BinaryBlobException e) {
		MergeResult<RawText> r = new MergeResult<>(Collections.<RawText>emptyList());
		r.setContainsConflicts(true);
		return r;
	}
	return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
			ourText, theirsText));
}
 
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: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) {
	List<DiffEntry> diffs = new ArrayList<>();
	try (	DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
			RevWalk revWalk = new RevWalk(repository);
			ObjectReader reader = repository.newObjectReader();) {
    	diffFormatter.setRepository(repository);
    	diffFormatter.setDetectRenames(true);
    	diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
    	
    	CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    	if (!oldRevId.equals(ObjectId.zeroId()))
    		oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
    	
    	CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
    	if (!newRevId.equals(ObjectId.zeroId()))
    		newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
    	
    	for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) {
    		if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
    				|| !Objects.equal(entry.getOldMode(), entry.getNewMode())
    				|| entry.getOldId()==null || !entry.getOldId().isComplete()
    				|| entry.getNewId()== null || !entry.getNewId().isComplete()
    				|| !entry.getOldId().equals(entry.getNewId())) {
    			diffs.add(entry);
    		}
    	}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}			
	return diffs;
}
 
Example #5
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected static DiffFormatter createDiffFormatter(Repository r, OutputStream buffer) {
    DiffFormatter formatter = new DiffFormatter(buffer);
    formatter.setRepository(r);
    formatter.setDiffComparator(RawTextComparator.DEFAULT);
    formatter.setDetectRenames(true);
    return formatter;
}
 
Example #6
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 5 votes vote down vote up
public ArrayList<String> getShortMessage() {
        for (RevCommit revision : walk) {
            shortMessage.add(revision.getShortMessage());
//[LOG]            logger.debug(revision.getShortMessage());
            DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
            df.setRepository(repository);
            df.setDiffComparator(RawTextComparator.DEFAULT);
            df.setDetectRenames(true);
            RevCommit parent = null;
            if(revision.getParentCount()!=0) {
                try {
                    parent = walk.parseCommit(revision.getParent(0).getId());
                    RevTree tree = revision.getTree();
                    List<DiffEntry> diffs = df.scan(parent.getTree(), revision.getTree());
                    for (DiffEntry diff : diffs) {
                        String changeType = diff.getChangeType().name();
                        if(changeType.equals(ADD)|| changeType.equals(MODIFY))
                        {
//[LOG]                            logger.debug(diff.getChangeType().name());
//[LOG]                            logger.debug(diff.getNewPath());
                            tempCommitHistory.add(diff.getNewPath());
                        }
                    }
                }catch (IOException ex) {
//[LOG]                    logger.debug("IOException", ex);
                }
            }
            commitSHA.add(commitCount,revision.name());
            commitHistory.add(commitCount++,new ArrayList<String>(tempCommitHistory));
            tempCommitHistory.clear();
        }
        walk.reset();
        return shortMessage;
    }
 
Example #7
Source File: JgitUtils.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generates the differences between the contents of the 2 files.
 *
 * @param baseFile
 *            The base file to examine.
 * @param patchFile
 *            The patch file to examine.
 * @return The iterator containing the differences.
 * @throws IOException
 *             if Exceptions occur while reading the file.
 */
public static Iterator<JgitDifference> getDifferences(File baseFile, File patchFile)
        throws IOException {
    if (diffAlgorithm == null) {
        diffAlgorithm = DiffAlgorithm.getAlgorithm(SupportedAlgorithm.HISTOGRAM);
    }

    final RawText baseFileRaw = new RawText(baseFile);
    final RawText patchFileRaw = new RawText(patchFile);

    return new JgitDifferenceIterator(diffAlgorithm.diff(RawTextComparator.DEFAULT,
            baseFileRaw, patchFileRaw), baseFileRaw, patchFileRaw);
}
 
Example #8
Source File: GitSCM.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
private List<Change> getChangesForCommitedFiles(String hash) throws IOException {
	RevWalk revWalk = new RevWalk(git.getRepository());
	RevCommit commit = revWalk.parseCommit(ObjectId.fromString(hash));

	if (commit.getParentCount() > 1) {
		revWalk.close();
		return new ArrayList<Change>();
	}

	RevCommit parentCommit = commit.getParentCount() > 0
			? revWalk.parseCommit(ObjectId.fromString(commit.getParent(0).getName()))
			: null;

	DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
	df.setBinaryFileThreshold(2048);
	df.setRepository(git.getRepository());
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);

	List<DiffEntry> diffEntries = df.scan(parentCommit, commit);
	df.close();
	revWalk.close();

	List<Change> changes = new ArrayList<Change>();
	for (DiffEntry entry : diffEntries) {
		Change change = new Change(entry.getNewPath(), entry.getOldPath(), 0, 0,
				ChangeType.valueOf(entry.getChangeType().name()));
		analyzeDiff(change, entry);
		changes.add(change);
	}

	return changes;
}
 
Example #9
Source File: JGitHelper.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
private Revision getRevisionObj(Repository repository, RevCommit commit) throws IOException {
    String commitSHA = commit.getName();
    Date commitTime = commit.getAuthorIdent().getWhen();
    String comment = commit.getFullMessage().trim();
    String user = commit.getAuthorIdent().getName();
    String emailId = commit.getAuthorIdent().getEmailAddress();
    List<ModifiedFile> modifiedFiles = new ArrayList<ModifiedFile>();
    if (commit.getParentCount() == 0) {
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(false);
        while (treeWalk.next()) {
            modifiedFiles.add(new ModifiedFile(treeWalk.getPathString(), "added"));
        }
    } else {
        RevWalk rw = new RevWalk(repository);
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(repository);
        diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
        diffFormatter.setDetectRenames(true);
        List<DiffEntry> diffEntries = diffFormatter.scan(parent.getTree(), commit.getTree());
        for (DiffEntry diffEntry : diffEntries) {
            modifiedFiles.add(new ModifiedFile(diffEntry.getNewPath(), getAction(diffEntry.getChangeType().name())));
        }
    }

    return new Revision(commitSHA, commitTime, comment, user, emailId, modifiedFiles);
}
 
Example #10
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 5 votes vote down vote up
static GitHistoryParser fromRepository(final Repository repository, final String testDefinitionDirectory) {
    final RevWalk revWalk = new RevWalk(repository);
    final DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
    df.setRepository(repository);
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(false); // to regard rename changes as add and remove
    return new GitHistoryParser(revWalk, df, testDefinitionDirectory);
}
 
Example #11
Source File: GitRepository.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
public DiffFormatter getDiffFormatter(OutputStream out) {
	DiffFormatter formatter = new DiffFormatter(out);
	formatter.setRepository(git.getRepository());
	formatter.setDiffComparator(RawTextComparator.DEFAULT);
	formatter.setDetectRenames(true);
	
	return formatter;
}
 
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: GitRevisionInformationProvider.java    From jdt-codemining with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RevisionInformation getRevisionInformation(IResource resource) {
	RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
	if (mapping == null) {
		return null;
	}
	Repository repository = mapping.getRepository();
	if (repository == null) {
		return null;
	}
	String path = mapping.getRepoRelativePath(resource);
	if (path == null) {
		return null;
	}
	final BlameCommand command = new BlameCommand(repository).setFollowFileRenames(true).setFilePath(path);
	try {
		command.setStartCommit(repository.resolve(Constants.HEAD));
	} catch (IOException e) {
		return null;
	}

	command.setTextComparator(RawTextComparator.WS_IGNORE_ALL);

	BlameResult result;
	try {
		result = command.call();
	} catch (Exception e1) {
		// Activator.error(e1.getMessage(), e1);
		return null;
	}
	// progress.worked(1);
	if (result == null)
		return null;

	RevisionInformation info = new RevisionInformation();
	Map<RevCommit, BlameRevision> revisions = new HashMap<>();
	int lineCount = result.getResultContents().size();
	BlameRevision previous = null;
	for (int i = 0; i < lineCount; i++) {
		RevCommit commit = result.getSourceCommit(i);
		String sourcePath = result.getSourcePath(i);
		if (commit == null) {
			// Unregister the current revision
			if (previous != null) {
				previous.register();
				previous = null;
			}
			continue;
		}
		BlameRevision revision = revisions.get(commit);
		if (revision == null) {
			revision = new ExtendedBlameRevision();
			revision.setRepository(repository);
			revision.setCommit(commit);
			revision.setSourcePath(sourcePath);
			revisions.put(commit, revision);
			info.addRevision(revision);
		}
		revision.addSourceLine(i, result.getSourceLine(i));
		if (previous != null)
			if (previous == revision)
				previous.addLine();
			else {
				previous.register();
				previous = revision.reset(i);
			}
		else
			previous = revision.reset(i);
	}
	if (previous != null)
		previous.register();
	return info;
}
 
Example #14
Source File: GitCommit.java    From compiler with Apache License 2.0 4 votes vote down vote up
private void updateChangedFiles(final RevCommit parent, final int parentIndex, final RevCommit child) {
	final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);

	try {
		final AbstractTreeIterator parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree());
		final AbstractTreeIterator childIter = new CanonicalTreeParser(null, repository.newObjectReader(), child.getTree());
		List<DiffEntry> diffs = df.scan(parentIter, childIter);
		for (final DiffEntry diff : diffs) {
			if (diff.getChangeType() == ChangeType.MODIFY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.MODIFIED);
				}
			// RENAMED file may have the same/different object id(s) for old and new
			} else if (diff.getChangeType() == ChangeType.RENAME) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.RENAMED);
				}
			} else if (diff.getChangeType() == ChangeType.COPY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.COPIED);
				}
			// ADDED file should not have old path and its old object id is 0's
			} else if (diff.getChangeType() == ChangeType.ADD) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.ADDED);
				}
			// DELETED file's new object id is 0's and doesn't have new path
			} else if (diff.getChangeType() == ChangeType.DELETE) {
				if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) {
					String oldPath = diff.getOldPath();
					String oldObjectId = diff.getOldId().toObjectId().getName();
					ChangedFile.Builder cfb = getChangedFile(oldPath, ChangeKind.DELETED);
					filePathGitObjectIds.put(oldPath, diff.getNewId().toObjectId());
				}
			}
		}
	} catch (final IOException e) {
		if (debug)
			System.err.println("Git Error getting commit diffs: " + e.getMessage());
	}
	df.close();
}