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

The following examples show how to use org.eclipse.jgit.diff.DiffEntry#getNewPath() . 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
/**
 * Add a {@link FlowEdge} to the {@link FlowGraph}. The method uses the {@link FlowEdgeFactory} instance
 * provided by the {@link FlowGraph} to build a {@link FlowEdge} from the edge config file.
 * @param change
 */
private void addFlowEdge(DiffEntry change) {
  if (checkFilePath(change.getNewPath(), EDGE_FILE_DEPTH)) {
    Path edgeFilePath = new Path(this.repositoryDir, change.getNewPath());
    try {
      Config edgeConfig = loadEdgeFileWithOverrides(edgeFilePath);
      List<SpecExecutor> specExecutors = getSpecExecutors(edgeConfig);
      Class flowEdgeFactoryClass = Class.forName(ConfigUtils.getString(edgeConfig, FlowGraphConfigurationKeys.FLOW_EDGE_FACTORY_CLASS,
          FlowGraphConfigurationKeys.DEFAULT_FLOW_EDGE_FACTORY_CLASS));
      FlowEdgeFactory flowEdgeFactory = (FlowEdgeFactory) GobblinConstructorUtils.invokeLongestConstructor(flowEdgeFactoryClass, edgeConfig);
      if (flowTemplateCatalog.isPresent()) {
        FlowEdge edge = flowEdgeFactory.createFlowEdge(edgeConfig, flowTemplateCatalog.get(), specExecutors);
        if (!this.flowGraph.addFlowEdge(edge)) {
          log.warn("Could not add edge {} to FlowGraph; skipping", edge.getId());
        } else {
          log.info("Added edge {} to FlowGraph", edge.getId());
        }
      } else {
        log.warn("Could not add edge defined in {} to FlowGraph as FlowTemplateCatalog is absent", change.getNewPath());
      }
    } catch (Exception e) {
      log.warn("Could not add edge defined in {} due to exception {}", change.getNewPath(), e.getMessage());
    }
  }
}
 
Example 3
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Add a {@link DataNode} to the {@link FlowGraph}. The method uses the {@link FlowGraphConfigurationKeys#DATA_NODE_CLASS} config
 * to instantiate a {@link DataNode} from the node config file.
 * @param change
 */
private void addDataNode(DiffEntry change) {
  if (checkFilePath(change.getNewPath(), NODE_FILE_DEPTH)) {
    Path nodeFilePath = new Path(this.repositoryDir, change.getNewPath());
    try {
      Config config = loadNodeFileWithOverrides(nodeFilePath);
      Class dataNodeClass = Class.forName(ConfigUtils.getString(config, FlowGraphConfigurationKeys.DATA_NODE_CLASS,
          FlowGraphConfigurationKeys.DEFAULT_DATA_NODE_CLASS));
      DataNode dataNode = (DataNode) GobblinConstructorUtils.invokeLongestConstructor(dataNodeClass, config);
      if (!this.flowGraph.addDataNode(dataNode)) {
        log.warn("Could not add DataNode {} to FlowGraph; skipping", dataNode.getId());
      } else {
        log.info("Added Datanode {} to FlowGraph", dataNode.getId());
      }
    } catch (Exception e) {
      log.warn("Could not add DataNode defined in {} due to exception {}", change.getNewPath(), e);
    }
  }
}
 
Example 4
Source File: GitConfigMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Add a {@link FlowSpec} for an added, updated, or modified flow config
 * @param change
 */
@Override
public void addChange(DiffEntry change) {
  if (checkConfigFilePath(change.getNewPath())) {
    Path configFilePath = new Path(this.repositoryDir, change.getNewPath());

    try {
      Config flowConfig = loadConfigFileWithFlowNameOverrides(configFilePath);

      this.flowCatalog.put(FlowSpec.builder()
          .withConfig(flowConfig)
          .withVersion(SPEC_VERSION)
          .withDescription(SPEC_DESCRIPTION)
          .build());
    } catch (IOException e) {
      log.warn("Could not load config file: " + configFilePath);
    }
  }
}
 
Example 5
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 6
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 7
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Add an element (i.e., a {@link DataNode}, or a {@link FlowEdge} to
 * the {@link FlowGraph} for an added, updated or modified node or edge file.
 * @param change
 */
@Override
public void addChange(DiffEntry change) {
  Path path = new Path(change.getNewPath());
  if (path.depth() == NODE_FILE_DEPTH) {
    addDataNode(change);
  } else if (path.depth() == EDGE_FILE_DEPTH) {
    addFlowEdge(change);
  }
}
 
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: 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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 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;
}