Java Code Examples for org.eclipse.jgit.revwalk.RevCommit#getTree()

The following examples show how to use org.eclipse.jgit.revwalk.RevCommit#getTree() . 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: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
@Override
public Churn churn(Repository repository, RevCommit currentCommit) 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);
       	
       	List<DiffEntry> diffs = DiffEntry.scan(tw);
       	DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
   		diffFormatter.setRepository(repository);
   		diffFormatter.setContext(0);
   		
       	int addedLines = 0;
   		int deletedLines = 0;
       	for (DiffEntry entry : diffs) {
   			FileHeader header = diffFormatter.toFileHeader(entry);
           	List<? extends HunkHeader> hunks = header.getHunks();
           	for (HunkHeader hunkHeader : hunks) {
           		for (Edit edit : hunkHeader.toEditList()) {
   					if (edit.getType() == Type.INSERT) {
   						addedLines += edit.getLengthB();
   					} else if (edit.getType() == Type.DELETE) {
   						deletedLines += edit.getLengthA();
   					} else if (edit.getType() == Type.REPLACE) {
   						deletedLines += edit.getLengthA();
   						addedLines += edit.getLengthB();
   					}
   				}
           	}
       	}
       	diffFormatter.close();
       	return new Churn(addedLines, deletedLines);
	}
	return null;
}
 
Example 2
Source File: LayoutHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@Nullable
static RevCommit loadOriginalCommit(@NotNull ObjectReader reader, @Nullable ObjectId cacheCommit) throws IOException {
  final RevWalk revWalk = new RevWalk(reader);
  if (cacheCommit != null) {
    final RevCommit revCommit = revWalk.parseCommit(cacheCommit);
    revWalk.parseTree(revCommit.getTree());

    final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes, reader, revCommit.getTree());
    while (!treeParser.eof()) {
      if (treeParser.getEntryPathString().equals(ENTRY_COMMIT_REF)) {
        return revWalk.parseCommit(treeParser.getEntryObjectId());
      }
      treeParser.next();
    }
  }
  return null;
}
 
Example 3
Source File: PGA.java    From coming with MIT License 6 votes vote down vote up
private void obtainDiff(Repository repository, RevCommit commit, List<String> paths) throws IOException, GitAPIException {
        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);

        // now try to find a specific file
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        for (String path : paths) {
            String filePath = SIVA_COMMITS_DIR + commit.getName() + "/" + path;
            File file = new File(filePath);
            if (!file.exists()) {
                treeWalk.setFilter(PathFilter.create(path));
                if (!treeWalk.next()) {
                    throw new IllegalStateException("Did not find expected file '" + path + "'");
                }

                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = repository.open(objectId);
                // and then one can the loader to read the file
//                loader.copyTo(System.out);
                loader.copyTo(FileUtils.openOutputStream(file));
            }
        }
    }
 
Example 4
Source File: VersionControlGit.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * Find package assets that are present at the specified commit.
 */
public List<String> getAssetsAtCommit(String commitId, String packagePath) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
        // use commit's tree to find the path
        RevTree tree = commit.getTree();
        try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(packagePath));
            List<String> assets = new ArrayList<>();
            while (treeWalk.next()) {
                if (treeWalk.getPathString().equals(packagePath + "/" + treeWalk.getNameString())) {
                    // direct member of package
                    assets.add(treeWalk.getNameString());
                }
            }
            return assets;
        }
        finally {
            revWalk.dispose();
        }
    }
}
 
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: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<DiffEntryWrapper> doCalculateCommitDiff(
        RevCommit oldCommit,
        RevCommit newCommit,
        ObjectReader reader,
        Git git,
        File repoDir,
        Set<String> excludedPathSet) throws Exception {

    if (Objects.equals(oldCommit.getId(), newCommit.getId())) {
        return Collections.emptyList();
    }

    if (Objects.equals(oldCommit.getTree().getId(), newCommit.getTree().getId())) {
        return Collections.emptyList();
    }

    RenameDetector detector = new RenameDetector(git.getRepository());
    AbstractTreeIterator oldTree = new CanonicalTreeParser(null, reader, oldCommit.getTree());
    AbstractTreeIterator newTree = new CanonicalTreeParser(null, reader, newCommit.getTree());

    List<DiffEntry> entries = git.diff()
            .setOldTree(oldTree)
            .setNewTree(newTree)
            .call();
    detector.reset();
    detector.addAll(entries);
    entries = detector.compute();

    return entries.stream()
            .filter(entry -> !excludedPathSet.contains(entry.getNewPath()))
            .map(entry -> {
                RawText oldText = newRawText(entry, DiffEntry.Side.OLD, reader);
                RawText newText = newRawText(entry, DiffEntry.Side.NEW, reader);
                return DiffEntryWrapper.builder()
                        .gitDir(repoDir)
                        .diffEntry(entry)
                        .editList(calculateEditList(oldText, newText))
                        .build();
            }).collect(Collectors.toList());
}
 
Example 7
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private void populateFileContents(Repository repository, RevCommit commit,
		List<String> filePaths, Map<String, String> fileContents, Set<String> repositoryDirectories) throws Exception {
	logger.info("Processing {} {} ...", repository.getDirectory().getParent().toString(), commit.getName());
	RevTree parentTree = commit.getTree();
	try (TreeWalk treeWalk = new TreeWalk(repository)) {
		treeWalk.addTree(parentTree);
		treeWalk.setRecursive(true);
		while (treeWalk.next()) {
			String pathString = treeWalk.getPathString();
			if(filePaths.contains(pathString)) {
				ObjectId objectId = treeWalk.getObjectId(0);
				ObjectLoader loader = repository.open(objectId);
				StringWriter writer = new StringWriter();
				IOUtils.copy(loader.openStream(), writer);
				fileContents.put(pathString, writer.toString());
			}
			if(pathString.endsWith(".java") && pathString.contains("/")) {
				String directory = pathString.substring(0, pathString.lastIndexOf("/"));
				repositoryDirectories.add(directory);
				//include sub-directories
				String subDirectory = new String(directory);
				while(subDirectory.contains("/")) {
					subDirectory = subDirectory.substring(0, subDirectory.lastIndexOf("/"));
					repositoryDirectories.add(subDirectory);
				}
			}
		}
	}
}
 
Example 8
Source File: GITStatusCrawler.java    From celerio with Apache License 2.0 5 votes vote down vote up
private static RevTree getTree(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on some filtering
    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    // and using commit's tree find the path
    RevTree tree = commit.getTree();
    return tree;
}
 
Example 9
Source File: GfsCreateStashTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getTreeOfWorkDirCommit_shouldContainTheStashedChanges() throws IOException {
  byte[] expected = someBytes();
  writeToGfs("/test_file.txt", expected);
  Result result = createStash(gfs).execute();
  RevCommit stash = result.getCommit();
  ObjectId tree = stash.getTree();
  byte[] actual = TreeUtils.readFile("/test_file.txt", tree, repo).getData();
  assertArrayEquals(expected, actual);
}
 
Example 10
Source File: WalkCommitTreeAdapter.java    From coderadar with MIT License 5 votes vote down vote up
@Override
public void walkCommitTree(
    String projectRoot, String name, WalkTreeCommandInterface commandInterface)
    throws UnableToWalkCommitTreeException {
  try {
    Git git = Git.open(new File(projectRoot));
    ObjectId commitId = git.getRepository().resolve(name);

    RevWalk walk = new RevWalk(git.getRepository());
    RevCommit commit = walk.parseCommit(commitId);
    RevTree tree = commit.getTree();
    TreeWalk treeWalk = new TreeWalk(git.getRepository());
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);

    while (treeWalk.next()) {
      if (!treeWalk.getPathString().endsWith(".java")
          || treeWalk.getPathString().contains("build")
          || treeWalk.getPathString().contains("out")
          || treeWalk.getPathString().contains("classes")
          || treeWalk.getPathString().contains("node_modules")
          || treeWalk.getPathString().contains("test")) {
        continue;
      }
      commandInterface.walkMethod(treeWalk.getPathString());
    }
    git.close();
  } catch (IOException e) {
    throw new UnableToWalkCommitTreeException(e.getMessage());
  }
}
 
Example 11
Source File: VersionControlGit.java    From mdw with Apache License 2.0 5 votes vote down vote up
public ObjectStream getRemoteContentStream(String branch, String path) throws Exception {
    ObjectId id = localRepo.resolve("refs/remotes/origin/" + branch);
    try (ObjectReader reader = localRepo.newObjectReader();
            RevWalk walk = new RevWalk(reader)) {
        RevCommit commit = walk.parseCommit(id);
        RevTree tree = commit.getTree();
        TreeWalk treewalk = TreeWalk.forPath(reader, path, tree);
        if (treewalk != null) {
            return reader.open(treewalk.getObjectId(0)).openStream();
        }
        else {
            return null;
        }
    }
}
 
Example 12
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Returns the blob information for the file at the specified path and commit
 *
 * @param repoItem
 * @param commit
 * @return
 * @throws Exception
 */
public byte[] getBlob(String repoItem, String commit) throws Exception
{
    byte[] data;

    String parentPath = repository.getDirectory().getParent();

    ObjectId commitId = repository.resolve(commit);

    ObjectReader reader = repository.newObjectReader();
    RevWalk revWalk = new RevWalk(reader);
    RevCommit revCommit = revWalk.parseCommit(commitId);
    RevTree tree = revCommit.getTree();
    TreeWalk treeWalk = TreeWalk.forPath(reader, repoItem, tree);

    if (treeWalk != null)
    {
        data = reader.open(treeWalk.getObjectId(0)).getBytes();
    }
    else
    {
        throw new IllegalStateException("Did not find expected file '" + repoItem + "'");
    }

    reader.release();

    return data;
}
 
Example 13
Source File: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private void addTrees(Map<SubtreeConfig, RevCommit> parentCommits, TreeWalk treeWalk)
		throws IOException {
	for (Map.Entry<SubtreeConfig, RevCommit> entry : parentCommits.entrySet()) {
		String directory = entry.getKey().getSubtreeDirectory();
		RevCommit parentCommit = entry.getValue();
		if (".".equals(directory)) {
			treeWalk.addTree(parentCommit.getTree());
		} else {
			byte[] prefix = directory.getBytes(RawParseUtils.UTF8_CHARSET);
			CanonicalTreeParser treeParser = new CanonicalTreeParser(prefix,
					treeWalk.getObjectReader(), parentCommit.getTree());
			treeWalk.addTree(treeParser);
		}
	}
}
 
Example 14
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public RevTree getTreeForCommit(Repository repository, String commitId) throws IOException {
    ObjectId commitObjectId = repository.resolve(commitId);

    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitObjectId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }
}
 
Example 15
Source File: GetDiffEntriesForCommitsAdapter.java    From coderadar with MIT License 4 votes vote down vote up
@Override
public List<DiffEntry> getDiffs(String projectRoot, String commitName1, String commitName2)
    throws UnableToGetDiffsFromCommitsException {
  try {
    Git git = Git.open(new File(projectRoot));
    Repository repository = git.getRepository();
    RevCommit commit1 = repository.parseCommit(ObjectId.fromString(commitName1));
    RevCommit commit2 = repository.parseCommit(ObjectId.fromString(commitName2));
    // change commits so that commit2 is the older one
    if (commit1.getCommitTime() > commit2.getCommitTime()) {
      RevCommit tmp = commit1;
      commit1 = commit2;
      commit2 = tmp;
    }

    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    ObjectId oldTree = commit1.getTree();
    oldTreeIter.reset(reader, oldTree);

    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    ObjectId newTree = commit2.getTree();
    newTreeIter.reset(reader, newTree);

    DiffFormatter df = new DiffFormatter(new ByteArrayOutputStream());
    df.setRepository(repository);
    List<DiffEntry> entries =
        df.scan(oldTreeIter, newTreeIter).stream()
            .map(
                diffEntry -> {
                  DiffEntry entry = new DiffEntry();
                  entry.setNewPath(diffEntry.getNewPath());
                  entry.setOldPath(diffEntry.getOldPath());
                  entry.setChangeType(
                      ChangeTypeMapper.jgitToCoderadar(diffEntry.getChangeType()).ordinal());
                  return entry;
                })
            .collect(Collectors.toList());
    git.close();
    return entries;
  } catch (IOException e) {
    throw new UnableToGetDiffsFromCommitsException(e.getMessage());
  }
}
 
Example 16
Source File: RepositoryS3.java    From github-bucket with ISC License 4 votes vote down vote up
private RevTree getRevTree() throws IOException {
    Ref ref = repository.exactRef(branch.getFullRef());
    RevCommit commit = new RevWalk(repository).parseCommit(ref.getObjectId());
    return commit.getTree();
}
 
Example 17
Source File: GfsCreateStash.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
private RevCommit makeWorkingDirectoryCommit(RevCommit indexCommit) throws IOException {
  AnyObjectId tree = indexCommit.getTree();
  List<RevCommit> parents = asList(parent, indexCommit);
  return createCommit(workingDirectoryMessage, tree, committer, committer, parents, repo);
}
 
Example 18
Source File: RootNode.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static RootNode fromCommit(RevCommit commit, GfsObjectService objService) throws IOException {
  return new RootNode(commit.getTree(), objService);
}
 
Example 19
Source File: GitFlowMetaData.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void loadGitRepository(File gitProjectRootDir) throws IOException, GitAPIException {
    gitRepo = openRepository(gitProjectRootDir);

    try (final Git git = new Git(gitRepo)) {

        // Check if remote exists.
        if (!isEmpty(remoteToPush)) {
            final List<RemoteConfig> remotes = git.remoteList().call();
            final boolean isRemoteExist = remotes.stream().anyMatch(remote -> remote.getName().equals(remoteToPush));
            if (!isRemoteExist) {
                final List<String> remoteNames = remotes.stream().map(RemoteConfig::getName).collect(Collectors.toList());
                throw new IllegalArgumentException(
                        format("The configured remote '%s' to push does not exist. Available remotes are %s", remoteToPush, remoteNames));
            }
        }

        boolean isLatestCommit = true;
        try {
            for (RevCommit commit : git.log().call()) {
                final String shortCommitId = commit.getId().abbreviate(7).name();
                logger.debug("Processing a commit: {}", shortCommitId);
                final RevTree tree = commit.getTree();

                try (final TreeWalk treeWalk = new TreeWalk(gitRepo)) {
                    treeWalk.addTree(tree);

                    // Path -> ObjectId
                    final Map<String, ObjectId> bucketObjectIds = new HashMap<>();
                    final Map<String, ObjectId> flowSnapshotObjectIds = new HashMap<>();
                    while (treeWalk.next()) {
                        if (treeWalk.isSubtree()) {
                            treeWalk.enterSubtree();
                        } else {
                            final String pathString = treeWalk.getPathString();
                            // TODO: what is this nth?? When does it get grater than 0? Tree count seems to be always 1..
                            if (pathString.endsWith("/" + BUCKET_FILENAME)) {
                                bucketObjectIds.put(pathString, treeWalk.getObjectId(0));
                            } else if (pathString.endsWith(GitFlowPersistenceProvider.SNAPSHOT_EXTENSION)) {
                                flowSnapshotObjectIds.put(pathString, treeWalk.getObjectId(0));
                            }
                        }
                    }

                    if (bucketObjectIds.isEmpty()) {
                        // No bucket.yml means at this point, all flows are deleted. No need to scan older commits because those are already deleted.
                        logger.debug("Tree at commit {} does not contain any " + BUCKET_FILENAME + ". Stop loading commits here.", shortCommitId);
                        return;
                    }

                    loadBuckets(gitRepo, commit, isLatestCommit, bucketObjectIds, flowSnapshotObjectIds);
                    isLatestCommit = false;
                }
            }
        } catch (NoHeadException e) {
            logger.debug("'{}' does not have any commit yet. Starting with empty buckets.", gitProjectRootDir);
        }

    }
}
 
Example 20
Source File: GfsCreateStash.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
private RevCommit makeWorkingDirectoryCommit(RevCommit indexCommit) throws IOException {
  AnyObjectId tree = indexCommit.getTree();
  List<RevCommit> parents = asList(parent, indexCommit);
  return createCommit(workingDirectoryMessage, tree, committer, committer, parents, repo);
}