Java Code Examples for org.eclipse.jgit.revwalk.RevWalk

The following examples show how to use org.eclipse.jgit.revwalk.RevWalk. These examples are extracted from open source projects. 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
public List<BlameResult> calculate(
        File repoDir,
        List<String> filePathList,
        String startRev) throws Exception {
    try (Git git = Git.open(repoDir);
            ObjectReader reader = git.getRepository().newObjectReader();
            RevWalk rw = new RevWalk(git.getRepository())) {
        RevCommit startCommit = rw.parseCommit(git.getRepository().resolve(startRev));
        List<BlameResult> resultList = new ArrayList<>();
        for (String filePath : filePathList) {
            BlameResult result = calculateBlame(filePath, startCommit, git);
            resultList.add(result);
        }
        return resultList;
    }
}
 
Example 2
Source Project: scava   Source File: GitManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Date getDateForRevision(VcsRepository repository, String revision) throws Exception {
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	walk.parseCommit(iterator.next());
	
	Date date = null;
	while (iterator.hasNext()) {
		RevCommit commit = iterator.next();
		if (commit.getId().getName().equals(revision)) {
			date = new Date(Long.valueOf(commit.getCommitTime())*1000); 
		}
	}
	
	repo.close();
	git.close();

	return date;
}
 
Example 3
Source Project: blueocean-plugin   Source File: GitUtils.java    License: MIT License 6 votes vote down vote up
@SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="JDK11 produces different bytecode - https://github.com/spotbugs/spotbugs/issues/756")
static byte[] readFile(Repository repository, String ref, String filePath) {
    try (ObjectReader reader = repository.newObjectReader()) {
        ObjectId branchRef = repository.resolve(ref); // repository.exactRef(ref);
        if (branchRef != null) { // for empty repositories, branchRef may be null
            RevWalk revWalk = new RevWalk(repository);
            RevCommit commit = revWalk.parseCommit(branchRef);
            // and using commit's tree find the path
            RevTree tree = commit.getTree();
            TreeWalk treewalk = TreeWalk.forPath(reader, filePath, tree);
            if (treewalk != null) {
                // use the blob id to read the file's data
                return reader.open(treewalk.getObjectId(0)).getBytes();
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return null;
}
 
Example 4
Source Project: Getaviz   Source File: GitCommit.java    License: Apache License 2.0 6 votes vote down vote up
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException {
	RevWalk revWalk = new RevWalk(repository);
	parent = revWalk.parseCommit(parent.getId());
	revWalk.close();
	ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE);
	DiffFormatter df = new DiffFormatter(put);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);
	List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
	for(DiffEntry e : diffs){
		df.format(e);
		String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable
		returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType()));
		put.reset();
	}
	df.close();
}
 
Example 5
Source Project: Getaviz   Source File: GitRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Tag> getTags() throws TagsNotAvailableException {
	List<Tag> result = new ArrayList<Tag>();
	try {
		Git del = new Git(delegateRepository);
		List<Ref> tags = del.tagList().call();
		del.close();
		RevWalk walk = new RevWalk(delegateRepository);
		for (Ref tag : tags){
			GitCommit commit = new GitCommit(delegateRepository, walk.parseCommit(tag.getObjectId()));
			GitTag wrapperTag = new GitTag(commit, createTagName(tag));
			result.add(wrapperTag);
			walk.close();
		}
		return result;
	} catch (Exception e) {
		throw new TagsNotAvailableException(e);
	}
}
 
Example 6
Source Project: verigreen   Source File: JGitOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isBranchContainsCommit(String branchName, String commitId) {
    
    boolean ans = false;
    RevWalk walk = new RevWalk(_repo);
    RevCommit commit;
    Ref ref;
    try {
        commit = walk.parseCommit(_repo.resolve(commitId + "^0"));
        ref = _repo.getRef(branchName);
        if (walk.isMergedInto(commit, walk.parseCommit(ref.getObjectId()))) {
            ans = true;
        }
        walk.dispose();
    } catch (Throwable e) {
        throw new RuntimeException(String.format(
                "Failed to check if commit [%s] is part of branch[%s]",
                commitId,
                branchName), e);
    }
    
    return ans;
}
 
Example 7
Source Project: verigreen   Source File: JGitOperator.java    License: Apache License 2.0 6 votes vote down vote up
boolean isRefBehind( Ref behind, Ref tracking ) throws IOException {
  RevWalk walk = new RevWalk( _git.getRepository() );
  try {
    RevCommit behindCommit = walk.parseCommit( behind.getObjectId() );
    RevCommit trackingCommit = walk.parseCommit( tracking.getObjectId() );
    walk.setRevFilter( RevFilter.MERGE_BASE );
    walk.markStart( behindCommit );
    walk.markStart( trackingCommit );
    RevCommit mergeBase = walk.next();
    walk.reset();
    walk.setRevFilter( RevFilter.ALL );
    int aheadCount = RevWalkUtils.count( walk, behindCommit, mergeBase );
    int behindCount = RevWalkUtils.count( walk, trackingCommit, mergeBase );
    
    return behindCount > aheadCount ? true:false;
  } catch (Throwable e) {
         throw new RuntimeException(String.format(
                 "Failed to check if [%s] behind [%s]",
                 behind,
                 tracking), e);
     } 
  finally {
    walk.dispose();
  }
}
 
Example 8
Source Project: orion.server   Source File: Tag.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private RevCommit parseCommit() {
	if (this.commit == null) {
		RevWalk rw = new RevWalk(db);
		RevObject any;
		try {
			any = rw.parseAny(this.ref.getObjectId());
			if (any instanceof RevTag) {
				this.tag = (RevTag) any;
				RevObject o = rw.peel(any);
				if (o instanceof RevCommit) {
					this.commit = (RevCommit) rw.peel(any);
				}
			} else if (any instanceof RevCommit) {
				this.commit = (RevCommit) any;
			}
		} catch (IOException e) {
		} finally {
			rw.dispose();
		}
	}
	return commit;
}
 
Example 9
@Override
public RebaseResponse extractMessage(Repository repository) throws IOException {
    List<RebaseTodoLine> rebaseTodoLines = repository.readRebaseTodo(getRebasePath(repository, DONE), false);
    // the last rebase_todo_line
    RebaseTodoLine line = rebaseTodoLines.get(rebaseTodoLines.size() - 1);

    try (RevWalk walk = new RevWalk(repository)) {
        ObjectReader or = repository.newObjectReader();
        RevCommit commitToPick = walk.parseCommit(or.resolve(line.getCommit()).iterator().next());

        String oldMessage = commitToPick.getFullMessage();

        RebaseResponse response = new RebaseResponse(false, RebaseResponse.Status.INTERACTIVE_EDIT);
        response.setMessage(oldMessage);

        return response;
    }
}
 
Example 10
Source Project: onedev   Source File: Project.java    License: MIT License 6 votes vote down vote up
@Nullable
public RevCommit getRevCommit(ObjectId revId, boolean mustExist) {
	if (commitCache == null)
		commitCache = new HashMap<>();
	RevCommit commit;
	Optional<RevCommit> optional = commitCache.get(revId);
	if (optional == null) {
		try (RevWalk revWalk = new RevWalk(getRepository())) {
			optional = Optional.fromNullable(GitUtils.parseCommit(revWalk, revId));
		}
		commitCache.put(revId, optional);
	}
	commit = optional.orNull();
	
	if (mustExist && commit == null)
		throw new ObjectNotFoundException("Unable to find commit associated with object id: " + revId);
	else
		return commit;
}
 
Example 11
Source Project: onedev   Source File: PullRequest.java    License: MIT License 6 votes vote down vote up
public Collection<RevCommit> getPendingCommits() {
	if (pendingCommits == null) {
		pendingCommits = new HashSet<>();
		Project project = getTargetProject();
		try (RevWalk revWalk = new RevWalk(project.getRepository())) {
			ObjectId headCommitId = ObjectId.fromString(getLatestUpdate().getHeadCommitHash());
			revWalk.markStart(revWalk.parseCommit(headCommitId));
			ObjectId targetHeadCommitId = ObjectId.fromString(getLatestUpdate().getTargetHeadCommitHash());
			revWalk.markUninteresting(revWalk.parseCommit(targetHeadCommitId));
			revWalk.forEach(c->pendingCommits.add(c));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return pendingCommits;
}
 
Example 12
Source Project: onedev   Source File: Build.java    License: MIT License 6 votes vote down vote up
/**
 * Get fixed issue numbers
 * 
 */
public Collection<Long> getFixedIssueNumbers() {
	if (fixedIssueNumbers == null) {
		fixedIssueNumbers = new HashSet<>();
		Build prevBuild = getStreamPrevious(null);
		if (prevBuild != null) {
			Repository repository = project.getRepository();
			try (RevWalk revWalk = new RevWalk(repository)) {
				revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getCommitHash())));
				revWalk.markUninteresting(revWalk.parseCommit(prevBuild.getCommitId()));

				RevCommit commit;
				while ((commit = revWalk.next()) != null) 
					fixedIssueNumbers.addAll(IssueUtils.parseFixedIssueNumbers(commit.getFullMessage()));
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} 
	}
	return fixedIssueNumbers;
}
 
Example 13
Source Project: onedev   Source File: PullRequestUpdate.java    License: MIT License 6 votes vote down vote up
public Collection<String> getChangedFiles() {
	if (changedFiles == null) {
		changedFiles = new HashSet<>();
		
		Repository repository = getRequest().getWorkProject().getRepository();
		try (	RevWalk revWalk = new RevWalk(repository);
				TreeWalk treeWalk = new TreeWalk(repository)) {
			RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
			RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
			RevCommit comparisonBaseCommit = revWalk.parseCommit(getRequest().getComparisonBase(baseCommit, headCommit));
			treeWalk.addTree(headCommit.getTree());
			treeWalk.addTree(comparisonBaseCommit.getTree());
			treeWalk.setFilter(TreeFilter.ANY_DIFF);
			while (treeWalk.next())
				changedFiles.add(treeWalk.getPathString());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return changedFiles;
}
 
Example 14
Source Project: onedev   Source File: BlobEditsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testRemoveFile() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	BlobEdits edits = new BlobEdits(Sets.newHashSet("/server/src/com/example/a//a.java"), Maps.newHashMap());
	ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test delete");
	
	try (RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevTree revTree = revWalk.parseCommit(newCommitId).getTree();
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/b/b.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/a.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/b.java", revTree));
	}
}
 
Example 15
Source Project: netbeans   Source File: GetCommonAncestorCommand.java    License: Apache License 2.0 6 votes vote down vote up
private GitRevisionInfo getSingleBaseCommit (RevWalk walk, List<RevCommit> commits) throws IOException {
    while (commits.size() > 1) {
        walk.reset();
        for (RevCommit c : commits) {
            walk.markStart(walk.parseCommit(c));
        }
        walk.setRevFilter(RevFilter.MERGE_BASE);
        commits.clear();
        for (RevCommit commit = walk.next(); commit != null; commit = walk.next()) {
            commits.add(commit);
        }
    }
    if (commits.isEmpty()) {
        return null;
    } else {
        return getClassFactory().createRevisionInfo(commits.get(0), getRepository());
    }
}
 
Example 16
Source Project: centraldogma   Source File: GitRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void testDoUpdateRef(String ref, ObjectId commitId, boolean tagExists) throws Exception {
    final org.eclipse.jgit.lib.Repository jGitRepo = mock(org.eclipse.jgit.lib.Repository.class);
    final RevWalk revWalk = mock(RevWalk.class);
    final RefUpdate refUpdate = mock(RefUpdate.class);

    lenient().when(jGitRepo.exactRef(ref)).thenReturn(tagExists ? mock(Ref.class) : null);
    lenient().when(jGitRepo.updateRef(ref)).thenReturn(refUpdate);

    lenient().when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.NEW);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.FAST_FORWARD);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.LOCK_FAILURE);
    assertThatThrownBy(() -> GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId))
            .isInstanceOf(StorageException.class);
}
 
Example 17
Source Project: piper   Source File: JGitTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private List<IdentifiableResource> getHeadFiles (Repository aRepository, String... aSearchPaths) {
  List<String> searchPaths = Arrays.asList(aSearchPaths);
  List<IdentifiableResource> resources = new ArrayList<>();
  try (ObjectReader reader = aRepository.newObjectReader(); RevWalk walk = new RevWalk(reader); TreeWalk treeWalk = new TreeWalk(aRepository,reader);) {
    final ObjectId id = aRepository.resolve(Constants.HEAD);
    if(id == null) {
      return List.of();
    }
    RevCommit commit = walk.parseCommit(id);
    RevTree tree = commit.getTree();
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
      String path = treeWalk.getPathString();        
      if(!path.startsWith(".") && (searchPaths == null || searchPaths.size() == 0 || searchPaths.stream().anyMatch((sp)->path.startsWith(sp)))) {
        ObjectId objectId = treeWalk.getObjectId(0);
        logger.debug("Loading {} [{}]",path,objectId.name());
        resources.add(readBlob(aRepository, path.substring(0, path.indexOf('.')), objectId.name()));
      }
    }
    return resources;
  }
  catch (Exception e) {
    throw Throwables.propagate(e);
  } 
}
 
Example 18
Source Project: onedev   Source File: GitUtilsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testMergeWithContentConflict() throws Exception {
	addFileAndCommit("initial", "", "initial");
	git.checkout().setCreateBranch(true).setName("dev").call();
	addFileAndCommit("dev1", "", "dev1");
	addFileAndCommit("conflict", "1", "dev2");
	git.checkout().setName("master").call();
	addFileAndCommit("master1", "", "master1");
	addFileAndCommit("conflict", "2", "master2");
	assertNull(GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
			git.getRepository().resolve("dev"), false, user, user, "merge commit", false));
	
	ObjectId mergeCommitId = GitUtils.merge(git.getRepository(), git.getRepository().resolve("master"), 
			git.getRepository().resolve("dev"), false, user, user, "merge commit", true);
	assertNotNull(mergeCommitId);
	
	try (	RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevCommit mergeCommit = revWalk.parseCommit(mergeCommitId);
		TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), "conflict", mergeCommit.getTree());
		BlobIdent blobIdent = new BlobIdent(mergeCommit.name(), "conflict", FileMode.REGULAR_FILE.getBits());
		Blob blob = new Blob(blobIdent, treeWalk.getObjectId(0), treeWalk.getObjectReader());
		assertEquals("2", blob.getText().getContent());
	}
	
}
 
Example 19
Source Project: apidiff   Source File: APIDiff.java    License: MIT License 6 votes vote down vote up
@Override
public Result detectChangeAllHistory(String branch, List<Classifier> classifiers) throws Exception {
	Result result = new Result();
	GitService service = new GitServiceImpl();
	Repository repository = service.openRepositoryAndCloneIfNotExists(this.path, this.nameProject, this.url);
	RevWalk revWalk = service.createAllRevsWalk(repository, branch);
	//Commits.
	Iterator<RevCommit> i = revWalk.iterator();
	while(i.hasNext()){
		RevCommit currentCommit = i.next();
		for(Classifier classifierAPI: classifiers){
			Result resultByClassifier = this.diffCommit(currentCommit, repository, this.nameProject, classifierAPI);
			result.getChangeType().addAll(resultByClassifier.getChangeType());
			result.getChangeMethod().addAll(resultByClassifier.getChangeMethod());
			result.getChangeField().addAll(resultByClassifier.getChangeField());
		}
	}
	this.logger.info("Finished processing.");
	return result;
}
 
Example 20
Source Project: GitFx   Source File: GitRepoMetaData.java    License: Apache License 2.0 5 votes vote down vote up
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException,
        MissingObjectException,
        IncorrectObjectTypeException {
    RevWalk walk = new RevWalk(repository) ;
    RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());
    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    oldTreeParser.reset(oldReader, tree.getId());
    walk.dispose();
    return oldTreeParser;
}
 
Example 21
Source Project: netbeans   Source File: CancelRevFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean include (RevWalk walker, RevCommit cmit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
    if (monitor.isCanceled()) {
        throw StopWalkException.INSTANCE;
    }
    return true;
}
 
Example 22
Source Project: go-plugins   Source File: JGitHelper.java    License: Apache License 2.0 5 votes vote down vote up
private Revision getRevisionObj(Repository repository, RevCommit commit) throws IOException {
    String commitSHA = commit.getName();
    Date commitTime = commit.getAuthorIdent().getWhen();
    String comment = commit.getFullMessage().trim();
    String user = commit.getAuthorIdent().getName();
    String emailId = commit.getAuthorIdent().getEmailAddress();
    List<ModifiedFile> modifiedFiles = new ArrayList<ModifiedFile>();
    if (commit.getParentCount() == 0) {
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(false);
        while (treeWalk.next()) {
            modifiedFiles.add(new ModifiedFile(treeWalk.getPathString(), "added"));
        }
    } else {
        RevWalk rw = new RevWalk(repository);
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(repository);
        diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
        diffFormatter.setDetectRenames(true);
        List<DiffEntry> diffEntries = diffFormatter.scan(parent.getTree(), commit.getTree());
        for (DiffEntry diffEntry : diffEntries) {
            modifiedFiles.add(new ModifiedFile(diffEntry.getNewPath(), getAction(diffEntry.getChangeType().name())));
        }
    }

    return new Revision(commitSHA, commitTime, comment, user, emailId, modifiedFiles);
}
 
Example 23
Source Project: gradle-gitsemver   Source File: Tags.java    License: Apache License 2.0 5 votes vote down vote up
private static TagAndVersion findLatestTopoTag(Repository repo, Map<ObjectId, Set<String>> allTags, String prefix)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {

    try {
        RevWalk walk = new RevWalk(repo);
        walk.markStart(walk.parseCommit(GitRepos.getHeadObjectId(repo)));
        for (RevCommit commit : walk) {
            ObjectId commitId = commit.getId();
            // Find the very first tag in history
            if (allTags.containsKey(commitId)) {
                List<TagAndVersion> foundTags = new LinkedList<TagAndVersion>();
                // If there are more than one tag for this commit, choose the lexographically superior one
                for (String tagName : allTags.get(commitId)) {
                    String tagVersion = GitRepos.stripVFromVersionString(tagName);
                    if (prefix == null) {
                        foundTags.add(new TagAndVersion(tagName, SemanticVersions.parse(tagVersion)));
                    } else {
                        foundTags.add(new TagAndVersion(tagName, SemanticVersions.parse(prefix, tagVersion)));
                    }
                }
                Collections.sort(foundTags);
                return foundTags.get(foundTags.size() - 1);
            }
        }
        // No tags found - return null
        return null;
    } catch (NullPointerException e) {
        return new TagAndVersion("0.0.0", new DefaultSemanticVersion(
                "0.0.0",
                0,
                0,
                0,
                null,
                null));
    }
}
 
Example 24
Source Project: mdw   Source File: VersionControlGit.java    License: 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 25
Source Project: SZZUnleashed   Source File: CommitUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a revision tree parser wich could be used to compare revisions and extract revision
 * files.
 *
 * @param commitId a unique ID for a commit in the repository.
 * @return a tree iterator that could iterate through the revision tree.
 */
private AbstractTreeIterator getCanonicalTreeParser(ObjectId commitId) throws IOException {
  try (RevWalk walk = new RevWalk(this.git.getRepository())) {
    RevCommit commit = walk.parseCommit(commitId);
    ObjectId treeId = commit.getTree().getId();
    try (ObjectReader reader = git.getRepository().newObjectReader()) {
      return new CanonicalTreeParser(null, reader, treeId);
    }
  }
}
 
Example 26
Source Project: repairnator   Source File: GitHelperTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testcomputePatchStats() throws GitAPIException, IOException {
    JobStatus jobStatus = new JobStatus("fakePomDirPath");

    String remoteRepo = "https://github.com/Spirals-Team/jtravis.git";
    String parentCommit = "2d65266f9a52b27f955ec9a74aa9ab4dac5537d7";
    String commit = "f267c73200e2ebb9431d6ffe80e507222567696c"; // GH says: 14 changed files, 443 additions, 104 deletions,
                                                                // on java files is: 13 changed files, 405 additions, 104 deletions
    tmpDir = java.nio.file.Files.createTempDirectory("jtravis").toFile();
    Git git = Git.cloneRepository().setURI(remoteRepo).setBranch("master").setDirectory(tmpDir).call();

    RevWalk revwalk = new RevWalk(git.getRepository());

    RevCommit revParentCommit = revwalk.parseCommit(ObjectId.fromString(parentCommit));
    RevCommit revCommit = revwalk.parseCommit(ObjectId.fromString(commit));

    GitHelper gitHelper = new GitHelper();
    gitHelper.computePatchStats(jobStatus, git, revCommit, revParentCommit);

    PatchDiff patchDiff = jobStatus.getProperties().getPatchDiff();

    assertEquals(8, patchDiff.getFiles().getNumberAdded());
    assertEquals(1, patchDiff.getFiles().getNumberDeleted());
    assertEquals(4, patchDiff.getFiles().getNumberChanged());
    assertEquals(405, patchDiff.getLines().getNumberAdded());
    assertEquals(104, patchDiff.getLines().getNumberDeleted());
}
 
Example 27
Source Project: onedev   Source File: OrRevFilter.java    License: MIT License 5 votes vote down vote up
@Override
public boolean include(RevWalk walker, RevCommit c)
		throws MissingObjectException, IncorrectObjectTypeException,
		IOException {
	for (RevFilter f : subfilters) {
		if (f.include(walker, c))
			return true;
	}
	return false;
}
 
Example 28
/**
 * Gets the merge base for the two given commits.
 * Danger -- the commits need to be from the given RevWalk or this will
 * fail in a not-completely-obvious way.
 */
private RevCommit getMergeBase(RevWalk walk, RevCommit commit1, RevCommit commit2)
    throws GitClientException {
  try {
    walk.setRevFilter(RevFilter.MERGE_BASE);
    walk.markStart(commit1);
    walk.markStart(commit2);
    return walk.next();
  } catch (Exception e) {
    throw new GitClientException(
        "Failed to get merge base commit for " + commit1 + " and " + commit2, e);
  }
}
 
Example 29
Source Project: orion.server   Source File: GitCommitHandlerV1.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private ObjectId getCommitObjectId(Repository db, ObjectId oid) throws MissingObjectException, IncorrectObjectTypeException, IOException {
	RevWalk walk = new RevWalk(db);
	try {
		return walk.parseCommit(oid);
	} finally {
		walk.close();
	}
}
 
Example 30
Source Project: gradle-gitsemver   Source File: Tags.java    License: Apache License 2.0 5 votes vote down vote up
private static TagAndVersion getLatestTagFromWalk(RevWalk walk, Map<ObjectId, Set<String>> tags, String prefix) {
    List<TagAndVersion> foundTags = findAllTagsOnWalk(walk, tags, prefix);
    if (foundTags.isEmpty()) {
        return null;
    } else {
        Collections.sort(foundTags);
        return foundTags.get(foundTags.size() - 1);
    }
}