org.eclipse.jgit.revwalk.RevWalk Java Examples

The following examples show how to use org.eclipse.jgit.revwalk.RevWalk. 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: BlameCalculator.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 File: GitUtilsTest.java    From onedev with 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 #3
Source File: GitManager.java    From scava with 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 #4
Source File: GitUtils.java    From blueocean-plugin with 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 #5
Source File: GitCommit.java    From Getaviz with 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 #6
Source File: GitRepository.java    From Getaviz with 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 #7
Source File: APIDiff.java    From apidiff with 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 #8
Source File: JGitTemplate.java    From piper with 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 #9
Source File: GitRepositoryTest.java    From centraldogma with 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 #10
Source File: GetCommonAncestorCommand.java    From netbeans with 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 #11
Source File: BlobEditsTest.java    From onedev with 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 #12
Source File: PullRequestUpdate.java    From onedev with 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 #13
Source File: JGitOperator.java    From verigreen with 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 #14
Source File: Build.java    From onedev with 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 #15
Source File: PullRequest.java    From onedev with 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 #16
Source File: JGitOperator.java    From verigreen with 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 #17
Source File: Project.java    From onedev with 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 #18
Source File: Tag.java    From orion.server with 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 #19
Source File: RewordActionHandler.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #20
Source File: DocumentationGitBasedManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private String getLastRevisionBeforeDate(VcsRepository repository, Date date) throws Exception
{
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	
	String revision="";
	// The commits are ordered latest first, so we want to find the fist that it is before the date
	int dateComparison;
	while(iterator.hasNext()) 
	{
		RevCommit commit = walk.parseCommit(iterator.next());
		dateComparison=new Date(Long.valueOf(commit.getCommitTime())*1000).compareTo(date);
		if (dateComparison < 0) {
			revision=commit.getId().getName();
			break;
		}
	}
	
	walk.close();
	repo.close();
	git.close();
	
	if(revision.isEmpty())
		return "";
	return revision;
}
 
Example #21
Source File: Project.java    From onedev with MIT License 5 votes vote down vote up
public InputStream getInputStream(BlobIdent ident) {
	try (RevWalk revWalk = new RevWalk(getRepository())) {
		ObjectId commitId = getObjectId(ident.revision, true);
		RevTree revTree = revWalk.parseCommit(commitId).getTree();
		TreeWalk treeWalk = TreeWalk.forPath(getRepository(), ident.path, revTree);
		if (treeWalk != null) {
			ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
			return objectLoader.openStream();
		} else {
			throw new ObjectNotFoundException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #22
Source File: Tags.java    From gradle-gitsemver with Apache License 2.0 5 votes vote down vote up
private static List<TagAndVersion> findAllTagsOnWalk(RevWalk walk,
                                                     Map<ObjectId, Set<String>> tags, String prefix) {
    List<TagAndVersion> foundTags = new LinkedList<TagAndVersion>();
    for (RevCommit commit : walk) {
        ObjectId commitId = commit.getId();
        if (tags.containsKey(commitId)) {
            addTagsToListForCommitId(foundTags, tags, commitId, prefix);
        }
    }
    return foundTags;
}
 
Example #23
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(RevCommit commit)
    throws IOException, MissingObjectException, IncorrectObjectTypeException {
  // from the commit we can build the tree which allows us to construct the TreeParser
  try (RevWalk walk = new RevWalk(repo)) {
    return prepareTreeParserHelper(walk, commit);
  }
}
 
Example #24
Source File: GitServiceImpl.java    From apidiff with MIT License 5 votes vote down vote up
@Override
public RevCommit createRevCommitByCommitId(final Repository repository, final String commitId) throws Exception{
	RevWalk walk = new RevWalk(repository);
	RevCommit commit = walk.parseCommit(repository.resolve(commitId));
	walk.parseCommit(commit.getParent(0));
	return commit;
}
 
Example #25
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 #26
Source File: DistanceCalculator.java    From jgitver with Apache License 2.0 5 votes vote down vote up
public Optional<Integer> distanceTo(ObjectId target) {
    DepthWalk.RevWalk walk = null;
    try {
        walk = new DepthWalk.RevWalk(repository, maxDepth);
        RevCommit startCommit = walk.parseCommit(startId);
        walk.markRoot(startCommit);
        walk.setRetainBody(false);

        Iterator<? extends RevCommit> commitIterator = walk.iterator();

        while (commitIterator.hasNext()) {
            RevCommit commit = commitIterator.next();
            
            if (commit.getId().getName().equals(target.getName())) {
                // we found it
                if (commit instanceof DepthWalk.Commit) {
                    DepthWalk.Commit dwc = (DepthWalk.Commit) commit;
                    return Optional.of(Integer.valueOf(dwc.getDepth()));
                } else {
                    throw new IllegalStateException(String.format(
                            "implementation of %s or jgit internal has been incorrectly changed",
                            DepthWalkDistanceCalculator.class.getSimpleName()
                    ));
                }
            }
        }
    } catch (IOException ignore) {
        ignore.printStackTrace();
    } finally {
        if (walk != null) {
            walk.dispose();
            walk.close();
        }
    }
    return Optional.empty();
}
 
Example #27
Source File: DefaultBuildManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public Collection<Long> queryNumbersOfStreamPrevious(Build build, Status status, int limit) {
	Map<ObjectId, Long> buildNumbers = new HashMap<>();
	for (Object[] fields: getSession().createQuery(buildQueryOfStreamPrevios(build, status, "commitHash", "number")).list()) {
		buildNumbers.put(ObjectId.fromString((String) fields[0]), (Long)fields[1]);
	}
	
	Collection<Long> prevBuildNumbers = new HashSet<>();
	if (!buildNumbers.isEmpty()) {
		try (RevWalk revWalk = new RevWalk(build.getProject().getRepository())) {
			revWalk.markStart(revWalk.lookupCommit(build.getCommitId()));
			RevCommit nextCommit;
			while ((nextCommit = revWalk.next()) != null) {
				Long buildNumber = buildNumbers.remove(nextCommit);
				if (buildNumber != null) {
					prevBuildNumbers.add(buildNumber);
					if (prevBuildNumbers.size() >= limit || buildNumbers.isEmpty())
						break;
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return prevBuildNumbers;
}
 
Example #28
Source File: DefaultCommitInfoManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Listen
public void on(RefUpdated event) {
	if (!event.getNewCommitId().equals(ObjectId.zeroId()) 
			&& (event.getRefName().startsWith(Constants.R_HEADS) 
					|| event.getRefName().startsWith(Constants.R_TAGS))) {
		try (RevWalk revWalk = new RevWalk(event.getProject().getRepository())) {
			RevCommit commit = GitUtils.parseCommit(revWalk, event.getNewCommitId());
			if (commit != null) {
				CollectingWork work = new CollectingWork(PRIORITY, commit, event.getRefName());
				batchWorkManager.submit(getBatchWorker(event.getProject().getId()), work);
			}
		}
	}
}
 
Example #29
Source File: CommitUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<RevCommit> toCommitList(RevWalk rw, int skip, int limit) {
  List<RevCommit> commits = new ArrayList<>();
  long max = (long) limit + skip;
  long count = 0;
  for(RevCommit commit : rw) {
    if(count >= skip && count < max)
      commits.add(commit);
    if(count++ >= max)
      break;
  }
  return unmodifiableList(commits);
}
 
Example #30
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Replicates ls-tree for the current commit.
 *
 * @return Map containing the full path and the data for all items in the repository.
 * @throws IOException
 */
public Map<String, byte[]> getAllMetadata() throws Exception
{
    Map<String, byte[]> contents = new HashMap<String, byte[]>();
    ObjectReader reader = repository.newObjectReader();
    ObjectId commitId = repository.resolve(curCommit);
    RevWalk revWalk = new RevWalk(reader);
    RevCommit commit = revWalk.parseCommit(commitId);
    RevTree tree = commit.getTree();
    TreeWalk treeWalk = new TreeWalk(reader);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(false);

    while (treeWalk.next())
    {
        if (treeWalk.isSubtree())
        {
            treeWalk.enterSubtree();
        }
        else
        {
            String member = treeWalk.getPathString();
            if (member.contains(SOURCEDIR))
            {
                byte[] data = getBlob(member, curCommit);
                contents.put(member, data);
            }
        }
    }

    reader.release();

    return contents;
}