Java Code Examples for org.eclipse.jgit.diff.DiffEntry#getChangeType()

The following examples show how to use org.eclipse.jgit.diff.DiffEntry#getChangeType() . 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: AbstractGitRepositoryTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected List<String> listFilesInCommit(Repository repository) throws IOException, GitAPIException {
    List<String> result = new ArrayList<>();
    try (Git git = new Git(repository)) {
        RevCommit commit = git.log().add(git.getRepository().resolve(Constants.MASTER)).call().iterator().next();
        if (commit.getParentCount() > 0) {
            try (TreeWalk treeWalk = new TreeWalk(repository)) {
                treeWalk.addTree(commit.getParent(0).getTree());
                treeWalk.addTree(commit.getTree());
                treeWalk.setRecursive(true);
                List<DiffEntry> diff = DiffEntry.scan(treeWalk, false, null);
                for (DiffEntry diffEntry : diff) {
                    if(diffEntry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                        result.add("-" + diffEntry.getOldPath());
                    } else {
                        result.add(diffEntry.getNewPath());
                    }
                }
            }
        }
    }
    Collections.sort(result);
    return result;
}
 
Example 2
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * A helper method where actual processing of the list of changes since the last refresh of the repository takes place
 * and the changes applied.
 * @throws IOException
 */
void processGitConfigChangesHelper(List<DiffEntry> changes) throws IOException {
  for (DiffEntry change : changes) {
    switch (change.getChangeType()) {
      case ADD:
      case MODIFY:
        addChange(change);
        break;
      case DELETE:
        removeChange(change);
        break;
      case RENAME:
        removeChange(change);
        addChange(change);
        break;
      default:
        throw new RuntimeException("Unsupported change type " + change.getChangeType());
    }
  }

  // Done processing changes, so checkpoint
  this.gitRepo.moveCheckpointAndHashesForward();
}
 
Example 3
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
  	BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.ADD) {
	blobIdent = new BlobIdent(oldRev, diffEntry.getOldPath(), diffEntry.getOldMode().getBits());
} else {
	blobIdent = new BlobIdent(oldRev, null, null);
}
return blobIdent;
  }
 
Example 4
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
private String statusOf(DiffEntry d) {
    switch (d.getChangeType()) {
    case ADD:       return "A";
    case MODIFY:    return "M";
    case DELETE:    return "D";
    case RENAME:    return "R"+d.getScore();
    case COPY:      return "C"+d.getScore();
    default:
        throw new AssertionError("Unexpected change type: "+d.getChangeType());
    }
}
 
Example 5
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public void fileTreeDiff(Repository repository, RevCommit currentCommit, List<String> javaFilesBefore, List<String> javaFilesCurrent, Map<String, String> renamedFilesHint) 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);

       	final RenameDetector rd = new RenameDetector(repository);
       	rd.setRenameScore(80);
       	rd.addAll(DiffEntry.scan(tw));

       	for (DiffEntry diff : rd.compute(tw.getObjectReader(), null)) {
       		ChangeType changeType = diff.getChangeType();
       		String oldPath = diff.getOldPath();
       		String newPath = diff.getNewPath();
       		if (changeType != ChangeType.ADD) {
        		if (isJavafile(oldPath)) {
        			javaFilesBefore.add(oldPath);
        		}
        	}
       		if (changeType != ChangeType.DELETE) {
        		if (isJavafile(newPath)) {
        			javaFilesCurrent.add(newPath);
        		}
       		}
       		if (changeType == ChangeType.RENAME && diff.getScore() >= rd.getRenameScore()) {
       			if (isJavafile(oldPath) && isJavafile(newPath)) {
       				renamedFilesHint.put(oldPath, newPath);
       			}
       		}
       	}
       }
}
 
Example 6
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private void notifyWatchers(Revision newRevision, List<DiffEntry> diffEntries) {
    for (DiffEntry entry : diffEntries) {
        switch (entry.getChangeType()) {
            case ADD:
                commitWatchers.notify(newRevision, entry.getNewPath());
                break;
            case MODIFY:
            case DELETE:
                commitWatchers.notify(newRevision, entry.getOldPath());
                break;
            default:
                throw new Error();
        }
    }
}
 
Example 7
Source File: BlobChange.java    From onedev with MIT License 5 votes vote down vote up
public BlobChange(String oldRev, String newRev, DiffEntry diffEntry, 
		WhitespaceOption whitespaceOption) {
	if (diffEntry.getChangeType() == ChangeType.RENAME 
			&& diffEntry.getOldPath().equals(diffEntry.getNewPath())) {
		// for some unknown reason, jgit detects rename even if path 
		// is the same
		type = ChangeType.MODIFY;
	} else {
		type = diffEntry.getChangeType();
	}
	this.whitespaceOption = whitespaceOption;
	oldBlobIdent = GitUtils.getOldBlobIdent(diffEntry, oldRev);
	newBlobIdent = GitUtils.getNewBlobIdent(diffEntry, newRev);
}
 
Example 8
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
  	BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.DELETE) {
	blobIdent = new BlobIdent(newRev, diffEntry.getNewPath(), diffEntry.getNewMode().getBits());
} else {
	blobIdent = new BlobIdent(newRev, null, null);
}
return blobIdent;
  }
 
Example 9
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Nullable
private Revision blockingFindLatestRevision(Revision lastKnownRevision, String pathPattern) {
    final RevisionRange range = normalizeNow(lastKnownRevision, Revision.HEAD);
    if (range.from().equals(range.to())) {
        // Empty range.
        return null;
    }

    if (range.from().major() == 1) {
        // Fast path: no need to compare because we are sure there is nothing at revision 1.
        final Map<String, Entry<?>> entries =
                blockingFind(range.to(), pathPattern, FindOptions.FIND_ONE_WITHOUT_CONTENT);
        return !entries.isEmpty() ? range.to() : null;
    }

    // Slow path: compare the two trees.
    final PathPatternFilter filter = PathPatternFilter.of(pathPattern);
    // Convert the revisions to Git trees.
    final List<DiffEntry> diffEntries;
    readLock();
    try (RevWalk revWalk = newRevWalk()) {
        final RevTree treeA = toTree(revWalk, range.from());
        final RevTree treeB = toTree(revWalk, range.to());
        diffEntries = blockingCompareTrees(treeA, treeB);
    } finally {
        readUnlock();
    }

    // Return the latest revision if the changes between the two trees contain the file.
    for (DiffEntry e : diffEntries) {
        final String path;
        switch (e.getChangeType()) {
            case ADD:
                path = e.getNewPath();
                break;
            case MODIFY:
            case DELETE:
                path = e.getOldPath();
                break;
            default:
                throw new Error();
        }

        if (filter.matches(path)) {
            return range.to();
        }
    }

    return null;
}
 
Example 10
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private Map<String, Change<?>> toChangeMap(List<DiffEntry> diffEntryList) {
    try (ObjectReader reader = jGitRepository.newObjectReader()) {
        final Map<String, Change<?>> changeMap = new LinkedHashMap<>();

        for (DiffEntry diffEntry : diffEntryList) {
            final String oldPath = '/' + diffEntry.getOldPath();
            final String newPath = '/' + diffEntry.getNewPath();

            switch (diffEntry.getChangeType()) {
                case MODIFY:
                    final EntryType oldEntryType = EntryType.guessFromPath(oldPath);
                    switch (oldEntryType) {
                        case JSON:
                            if (!oldPath.equals(newPath)) {
                                putChange(changeMap, oldPath, Change.ofRename(oldPath, newPath));
                            }

                            final JsonNode oldJsonNode =
                                    Jackson.readTree(
                                            reader.open(diffEntry.getOldId().toObjectId()).getBytes());
                            final JsonNode newJsonNode =
                                    Jackson.readTree(
                                            reader.open(diffEntry.getNewId().toObjectId()).getBytes());
                            final JsonPatch patch =
                                    JsonPatch.generate(oldJsonNode, newJsonNode, ReplaceMode.SAFE);

                            if (!patch.isEmpty()) {
                                putChange(changeMap, newPath,
                                          Change.ofJsonPatch(newPath, Jackson.valueToTree(patch)));
                            }
                            break;
                        case TEXT:
                            final String oldText = sanitizeText(new String(
                                    reader.open(diffEntry.getOldId().toObjectId()).getBytes(), UTF_8));

                            final String newText = sanitizeText(new String(
                                    reader.open(diffEntry.getNewId().toObjectId()).getBytes(), UTF_8));

                            if (!oldPath.equals(newPath)) {
                                putChange(changeMap, oldPath, Change.ofRename(oldPath, newPath));
                            }

                            if (!oldText.equals(newText)) {
                                putChange(changeMap, newPath,
                                          Change.ofTextPatch(newPath, oldText, newText));
                            }
                            break;
                        default:
                            throw new Error("unexpected old entry type: " + oldEntryType);
                    }
                    break;
                case ADD:
                    final EntryType newEntryType = EntryType.guessFromPath(newPath);
                    switch (newEntryType) {
                        case JSON: {
                            final JsonNode jsonNode = Jackson.readTree(
                                    reader.open(diffEntry.getNewId().toObjectId()).getBytes());

                            putChange(changeMap, newPath, Change.ofJsonUpsert(newPath, jsonNode));
                            break;
                        }
                        case TEXT: {
                            final String text = sanitizeText(new String(
                                    reader.open(diffEntry.getNewId().toObjectId()).getBytes(), UTF_8));

                            putChange(changeMap, newPath, Change.ofTextUpsert(newPath, text));
                            break;
                        }
                        default:
                            throw new Error("unexpected new entry type: " + newEntryType);
                    }
                    break;
                case DELETE:
                    putChange(changeMap, oldPath, Change.ofRemoval(oldPath));
                    break;
                default:
                    throw new Error();
            }
        }
        return changeMap;
    } catch (Exception e) {
        throw new StorageException("failed to convert list of DiffEntry to Changes map", e);
    }
}
 
Example 11
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected DiffInfo createDiffInfo(DiffEntry diffEntry, String diff) {
    return new DiffInfo(diffEntry.getChangeType(), diffEntry.getNewPath(), toInt(diffEntry.getNewMode()), diffEntry.getOldPath(), toInt(diffEntry.getOldMode()), diff);
}
 
Example 12
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 13
Source File: GitServiceImpl.java    From apidiff with MIT License 4 votes vote down vote up
@Override
public Map<ChangeType, List<GitFile>> fileTreeDiff(Repository repository, RevCommit commitNew) throws Exception {
       
	Map<ChangeType, List<GitFile>> mapDiff = new HashMap<ChangeType, List<GitFile>>();
	mapDiff.put(ChangeType.ADD, new ArrayList<>());
	mapDiff.put(ChangeType.COPY, new ArrayList<>());
	mapDiff.put(ChangeType.DELETE, new ArrayList<>());
	mapDiff.put(ChangeType.MODIFY, new ArrayList<>());
	mapDiff.put(ChangeType.RENAME, new ArrayList<>());
	
	if(commitNew.getParentCount() == 0){
		this.logger.warn("Commit don't have parent [commitId="+commitNew.getId().getName()+"]");
		return mapDiff;
	}
      
	ObjectId headOld = commitNew.getParent(0).getTree(); //Commit pai no grafo.
	ObjectId headNew = commitNew.getTree(); //Commit corrente.

       // prepare the two iterators to compute the diff between
	ObjectReader reader = repository.newObjectReader();
	
	CanonicalTreeParser treeRepositoryOld = new CanonicalTreeParser();
	treeRepositoryOld.reset(reader, headOld);
	
	CanonicalTreeParser treeRepositoryNew = new CanonicalTreeParser();
	treeRepositoryNew.reset(reader, headNew);
	
	// finally get the list of changed files
	List<DiffEntry> diffs = new Git(repository).diff()
	                    .setNewTree(treeRepositoryNew)
	                    .setOldTree(treeRepositoryOld)
	                    .setShowNameAndStatusOnly(true)
	                    .call();
	
       for (DiffEntry entry : diffs) {
       	if(UtilTools.isJavaFile(entry.getOldPath()) || UtilTools.isJavaFile(entry.getNewPath())) {
       		String pathNew =  "/dev/null".equals(entry.getNewPath())?null:entry.getNewPath();
       		String pathOld =  "/dev/null".equals(entry.getOldPath())?null:entry.getOldPath();
       		GitFile file = new GitFile(pathOld, pathNew, entry.getChangeType());
       		mapDiff.get(entry.getChangeType()).add(file);
       	}
       }
       return mapDiff;
}
 
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();
}
 
Example 15
Source File: LocalFacade.java    From sputnik with Apache License 2.0 4 votes vote down vote up
private boolean isNotDeleted(DiffEntry aDiffEntry) {
    return aDiffEntry.getChangeType() != ChangeType.DELETE;
}
 
Example 16
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
private List<RepoOperation> processDiffEntry(Git git, List<DiffEntry> diffEntries, ObjectId commitId)
        throws GitAPIException {
    List<RepoOperation> toReturn = new ArrayList<RepoOperation>();

    for (DiffEntry diffEntry : diffEntries) {

        // Update the paths to have a preceding separator
        String pathNew = FILE_SEPARATOR + diffEntry.getNewPath();
        String pathOld = FILE_SEPARATOR + diffEntry.getOldPath();

        RepoOperation repoOperation = null;
        Iterable<RevCommit> iterable = null;
        RevCommit latestCommit = null;
        ZonedDateTime commitTime = null;
        String author = null;
        switch (diffEntry.getChangeType()) {
            case ADD:
                iterable = git.log().addPath(diffEntry.getNewPath()).setMaxCount(1).call();
                latestCommit = iterable.iterator().next();
                if (latestCommit == null) {
                    iterable = git.log().setMaxCount(1).call();
                    latestCommit = iterable.iterator().next();
                }
                commitTime = Instant.ofEpochSecond(latestCommit.getCommitTime()).atZone(UTC);
                author = latestCommit.getAuthorIdent().getName();
                repoOperation = new RepoOperation(CREATE, pathNew, commitTime, null,
                        latestCommit.getId().getName());
                break;
            case MODIFY:
                iterable = git.log().addPath(diffEntry.getNewPath()).setMaxCount(1).call();
                latestCommit = iterable.iterator().next();
                if (latestCommit == null) {
                    iterable = git.log().setMaxCount(1).call();
                    latestCommit = iterable.iterator().next();
                }
                commitTime = Instant.ofEpochSecond(latestCommit.getCommitTime()).atZone(UTC);
                author = latestCommit.getAuthorIdent().getName();
                repoOperation = new RepoOperation(UPDATE, pathNew, commitTime, null,
                        latestCommit.getId().getName());
                break;
            case DELETE:
                iterable = git.log().addPath(diffEntry.getOldPath()).setMaxCount(1).call();
                latestCommit = iterable.iterator().next();
                if (latestCommit == null) {
                    iterable = git.log().setMaxCount(1).call();
                    latestCommit = iterable.iterator().next();
                }
                commitTime = Instant.ofEpochSecond(latestCommit.getCommitTime()).atZone(UTC);
                author = latestCommit.getAuthorIdent().getName();
                repoOperation = new RepoOperation(DELETE, pathOld, commitTime, null,
                        latestCommit.getId().getName());
                break;
            case RENAME:
                iterable = git.log().addPath(diffEntry.getOldPath()).setMaxCount(1).call();
                latestCommit = iterable.iterator().next();
                if (latestCommit == null) {
                    iterable = git.log().setMaxCount(1).call();
                    latestCommit = iterable.iterator().next();
                }
                commitTime = Instant.ofEpochSecond(latestCommit.getCommitTime()).atZone(UTC);
                author = latestCommit.getAuthorIdent().getName();
                repoOperation = new RepoOperation(MOVE, pathOld, commitTime, pathNew, commitId.getName());
                break;
            case COPY:
                iterable = git.log().addPath(diffEntry.getNewPath()).setMaxCount(1).call();
                latestCommit = iterable.iterator().next();
                if (latestCommit == null) {
                    iterable = git.log().setMaxCount(1).call();
                    latestCommit = iterable.iterator().next();
                }
                commitTime = Instant.ofEpochSecond(latestCommit.getCommitTime()).atZone(UTC);
                author = latestCommit.getAuthorIdent().getName();
                repoOperation = new RepoOperation(COPY, pathNew, commitTime, null, commitId.getName());
                break;
            default:
                logger.error("Error: Unknown git operation " + diffEntry.getChangeType());
                break;
        }
        if ((repoOperation != null) && (!repoOperation.getPath().endsWith(".keep"))) {
            repoOperation.setAuthor(StringUtils.isEmpty(author) ? "N/A" : author);
            toReturn.add(repoOperation);
        }
    }
    return toReturn;
}
 
Example 17
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
private boolean hasNewPath(DiffEntry d) {
    return d.getChangeType()==ChangeType.COPY || d.getChangeType()==ChangeType.RENAME;
}
 
Example 18
Source File: TreeRevFilter.java    From onedev with MIT License 4 votes vote down vote up
private static boolean isRename(DiffEntry ent) {
	return ent.getChangeType() == ChangeType.RENAME
			|| ent.getChangeType() == ChangeType.COPY;
}