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

The following examples show how to use org.eclipse.jgit.diff.DiffEntry#getOldPath() . 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: GitHistoryParser.java    From proctor with Apache License 2.0 6 votes vote down vote up
private Set<String> getModifiedTests(final RevCommit commit) throws IOException {
    final RevCommit[] parents = commit.getParents();
    final Set<String> result = new HashSet<>();
    if (parents.length == 1) { // merge commit if length > 1
        final RevCommit parent = revWalk.parseCommit(parents[0].getId());
        // get diff of this commit to its parent, as list of paths
        final List<DiffEntry> diffs = getDiffEntries(commit, parent);
        for (final DiffEntry diff : diffs) {
            final String changePath = diff.getChangeType().equals(DiffEntry.ChangeType.DELETE) ? diff.getOldPath() : diff.getNewPath();
            final Matcher testNameMatcher = testNamePattern.matcher(changePath);

            if (testNameMatcher.matches()) {
                final String testName = testNameMatcher.group(1);
                result.add(testName);
            }
        }
    }
    return result;
}
 
Example 2
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a {@link FlowEdge} from the {@link FlowGraph}. The method uses {@link FlowEdgeFactory}
 * to construct the edgeId of the {@link FlowEdge} from the config file and uses it to delete the associated
 * {@link FlowEdge}.
 * @param change
 */
private void removeFlowEdge(DiffEntry change) {
  if (checkFilePath(change.getOldPath(), EDGE_FILE_DEPTH)) {
    Path edgeFilePath = new Path(this.repositoryDir, change.getOldPath());
    try {
      Config config = getEdgeConfigWithOverrides(ConfigFactory.empty(), edgeFilePath);
      String edgeId = config.getString(FlowGraphConfigurationKeys.FLOW_EDGE_ID_KEY);
      if (!this.flowGraph.deleteFlowEdge(edgeId)) {
        log.warn("Could not remove edge {} from FlowGraph; skipping", edgeId);
      } else {
        log.info("Removed edge {} from FlowGraph", edgeId);
      }
    } catch (Exception e) {
      log.warn("Could not remove edge defined in {} due to exception {}", edgeFilePath, e.getMessage());
    }
  }
}
 
Example 3
Source File: GitConfigMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * remove a {@link FlowSpec} for a deleted or renamed flow config
 * @param change
 */
@Override
public void removeChange(DiffEntry change) {
  if (checkConfigFilePath(change.getOldPath())) {
    Path configFilePath = new Path(this.repositoryDir, change.getOldPath());
    String flowName = FSSpecStore.getSpecName(configFilePath);
    String flowGroup = FSSpecStore.getSpecGroup(configFilePath);

    // build a dummy config to get the proper URI for delete
    Config dummyConfig = ConfigBuilder.create()
        .addPrimitive(ConfigurationKeys.FLOW_GROUP_KEY, flowGroup)
        .addPrimitive(ConfigurationKeys.FLOW_NAME_KEY, flowName)
        .build();

    FlowSpec spec = FlowSpec.builder()
        .withConfig(dummyConfig)
        .withVersion(SPEC_VERSION)
        .withDescription(SPEC_DESCRIPTION)
        .build();

      this.flowCatalog.remove(spec.getUri());
  }
}
 
Example 4
Source File: CacheableCompareTreesCall.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
protected int weigh(List<DiffEntry> value) {
    int weight = SHA1_LEN * 2;
    for (DiffEntry e : value) {
        if (e.getOldId() != null) {
            weight += SHA1_LEN;
        }
        if (e.getNewId() != null) {
            weight += SHA1_LEN;
        }
        if (e.getOldPath() != null) {
            weight += e.getOldPath().length();
        }
        if (e.getNewPath() != null) {
            weight += e.getNewPath().length();
        }
        final Attribute attr = e.getDiffAttribute();
        if (attr != null) {
            if (attr.getKey() != null) {
                weight += attr.getKey().length();
            }
            if (attr.getValue() != null) {
                weight += attr.getValue().length();
            }
        }
    }
    return weight;
}
 
Example 5
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 6
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a {@link DataNode} from the {@link FlowGraph}. The method extracts the nodeId of the
 * {@link DataNode} from the node config file and uses it to delete the associated {@link DataNode}.
 * @param change
 */
private void removeDataNode(DiffEntry change) {
  if (checkFilePath(change.getOldPath(), NODE_FILE_DEPTH)) {
    Path nodeFilePath = new Path(this.repositoryDir, change.getOldPath());
    Config config = getNodeConfigWithOverrides(ConfigFactory.empty(), nodeFilePath);
    String nodeId = config.getString(FlowGraphConfigurationKeys.DATA_NODE_ID_KEY);
    if (!this.flowGraph.deleteDataNode(nodeId)) {
      log.warn("Could not remove DataNode {} from FlowGraph; skipping", nodeId);
    } else {
      log.info("Removed DataNode {} from FlowGraph", nodeId);
    }
  }
}
 
Example 7
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 8
Source File: ExtractProjectCommitsAdapter.java    From coderadar with MIT License 5 votes vote down vote up
/**
 * @param diff The diff entry to check.
 * @return Correct path for the current diffEntry.
 */
private String getFilepathFromDiffEntry(DiffEntry diff) {
  if (diff.getChangeType().equals(DiffEntry.ChangeType.DELETE)) {
    return diff.getOldPath();
  } else {
    return diff.getNewPath();
  }
}
 
Example 9
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 10
Source File: GitCommit.java    From compiler with Apache License 2.0 5 votes vote down vote up
private void updateChangedFiles(final RevCommit parent, final RevCommit child, final DiffEntry diff, final ChangeKind kind) {
	String newPath = diff.getNewPath();
	String newObjectId = diff.getNewId().toObjectId().getName();
	String oldPath = diff.getOldPath();
	String oldObjectId = diff.getOldId().toObjectId().getName();
	ChangedFile.Builder cfb = getChangedFile(newPath, kind);
	cfb.addChanges(kind);
	if (!oldPath.equals(newPath))
		cfb.addPreviousNames(oldPath);
	filePathGitObjectIds.put(newPath, diff.getNewId().toObjectId());
}
 
Example 11
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Remove an element (i.e. either a {@link DataNode} or a {@link FlowEdge} from the {@link FlowGraph} for
 * a renamed or deleted {@link DataNode} or {@link FlowEdge} file.
 * @param change
 */
@Override
public void removeChange(DiffEntry change) {
  Path path = new Path(change.getOldPath());
  if (path.depth() == NODE_FILE_DEPTH) {
    removeDataNode(change);
  } else if (path.depth() == EDGE_FILE_DEPTH) {
    removeFlowEdge(change);
  }
}
 
Example 12
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 13
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 14
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 15
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 16
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 17
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 18
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;
}