Java Code Examples for org.eclipse.jgit.revwalk.RevWalk#dispose()

The following examples show how to use org.eclipse.jgit.revwalk.RevWalk#dispose() . 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: 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 2
Source File: GitConnector.java    From compiler with Apache License 2.0 6 votes vote down vote up
public List<String> logCommitIds() {
	List<String> commits = new ArrayList<String>();
	RevWalk temprevwalk = new RevWalk(repository);
	try {
		revwalk.reset();
		Set<RevCommit> heads = getHeads();
		revwalk.markStart(heads);
		revwalk.sort(RevSort.TOPO, true);
		revwalk.sort(RevSort.COMMIT_TIME_DESC, true);
		revwalk.sort(RevSort.REVERSE, true);
		for (final RevCommit rc : revwalk)
			commits.add(rc.getName());
	} catch (final IOException e) {
		e.printStackTrace();
	} finally {
		temprevwalk.dispose();
		temprevwalk.close();
	}
	return commits;
}
 
Example 3
Source File: GitConnector.java    From compiler with Apache License 2.0 6 votes vote down vote up
public void countChangedFiles(List<String> commits, Map<String, Integer> counts) {
	RevWalk temprevwalk = new RevWalk(repository);
	try {
		revwalk.reset();
		Set<RevCommit> heads = getHeads();
		revwalk.markStart(heads);
		revwalk.sort(RevSort.TOPO, true);
		revwalk.sort(RevSort.COMMIT_TIME_DESC, true);
		revwalk.sort(RevSort.REVERSE, true);
		for (final RevCommit rc: revwalk) {
			final GitCommit gc = new GitCommit(this, repository, temprevwalk, projectName);
			System.out.println(rc.getName());
			commits.add(rc.getName());
			int count = gc.countChangedFiles(rc);
			counts.put(rc.getName(), count);
		}
	} catch (final IOException e) {
		if (debug)
			System.err.println("Git Error getting parsing HEAD commit for " + path + ". " + e.getMessage());
	} finally {
		temprevwalk.dispose();
		temprevwalk.close();
	}
}
 
Example 4
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 5
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 6
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
@Override
public Churn churnAtCommit(Repository repository, String commitId, RefactoringHandler handler) {
	GitService gitService = new GitServiceImpl();
	RevWalk walk = new RevWalk(repository);
	try {
		RevCommit commit = walk.parseCommit(repository.resolve(commitId));
		if (commit.getParentCount() > 0) {
			walk.parseCommit(commit.getParent(0));
			return gitService.churn(repository, commit);
		}
		else {
			logger.warn(String.format("Ignored revision %s because it has no parent", commitId));
		}
	} catch (MissingObjectException moe) {
		logger.warn(String.format("Ignored revision %s due to missing commit", commitId), moe);
	} catch (Exception e) {
		logger.warn(String.format("Ignored revision %s due to error", commitId), e);
		handler.handleException(commitId, e);
	} finally {
		walk.close();
		walk.dispose();
	}
	return null;
}
 
Example 7
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public void detectAll(Repository repository, String branch, final RefactoringHandler handler) throws Exception {
	GitService gitService = new GitServiceImpl() {
		@Override
		public boolean isCommitAnalyzed(String sha1) {
			return handler.skipCommit(sha1);
		}
	};
	RevWalk walk = gitService.createAllRevsWalk(repository, branch);
	try {
		detect(gitService, repository, handler, walk.iterator());
	} finally {
		walk.dispose();
	}
}
 
Example 8
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public int countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 9
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public void fetchAndDetectNew(Repository repository, final RefactoringHandler handler) throws Exception {
	GitService gitService = new GitServiceImpl() {
		@Override
		public boolean isCommitAnalyzed(String sha1) {
			return handler.skipCommit(sha1);
		}
	};
	RevWalk walk = gitService.fetchAndCreateNewRevsWalk(repository);
	try {
		detect(gitService, repository, handler, walk.iterator());
	} finally {
		walk.dispose();
	}
}
 
Example 10
Source File: GitServiceImpl.java    From apidiff with MIT License 5 votes vote down vote up
@Override
public Integer countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 11
Source File: PGA.java    From coming with MIT License 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(repository.resolve(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser treeParser = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    treeParser.reset(reader, tree.getId());

    walk.dispose();

    return treeParser;
}
 
Example 12
Source File: GitRepoMetaData.java    From GitFx with 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 13
Source File: TreeWalkingDiffDetector.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
public boolean hasChangedSince(String modulePath, java.util.List<String> childModules, Collection<AnnotatedTag> tags) throws IOException {
    RevWalk walk = new RevWalk(repo);
    try {
        walk.setRetainBody(false);
        walk.markStart(walk.parseCommit(repo.getRefDatabase().findRef("HEAD").getObjectId()));
        filterOutOtherModulesChanges(modulePath, childModules, walk);
        stopWalkingWhenTheTagsAreHit(tags, walk);
        return walk.iterator().hasNext();
    } finally {
        walk.dispose();
    }
}
 
Example 14
Source File: ChangeApplier.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private Collection<RevTag> findMatchingTags(String[] changeDescriptions) throws GitAPIException {
    final Set<String> changes = new HashSet<>(asList(changeDescriptions));
    final RevWalk revWalk = new RevWalk(repository);
    final List<RevTag> matchingTags = git.tagList().call().stream().map(ref -> {
        try {
            return revWalk.parseTag(ref.getObjectId());
        } catch (IOException e) {
            throw new RuntimeException("Unable to find tag for " + ref.getObjectId(), e);
        }
    }).filter(revTag -> changes.contains(revTag.getFullMessage().trim()))
        .collect(Collectors.toList());
    revWalk.dispose();
    return matchingTags;
}
 
Example 15
Source File: CommitPatch.java    From repairnator with MIT License 4 votes vote down vote up
@Override
protected StepStatus businessExecute() {
    if (this.getConfig().isPush()) {
        if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) {
            this.getLogger().info("Commit human patch...");
        } else {
            this.getLogger().info("Commit info from repair tools...");
        }

        super.setCommitType(this.commitType);

        try {
            Git git = Git.open(new File(this.getInspector().getRepoToPushLocalPath()));
            Ref oldHeadRef = git.getRepository().exactRef("HEAD");

            RevWalk revWalk = new RevWalk(git.getRepository());
            RevCommit headRev = revWalk.parseCommit(oldHeadRef.getObjectId());
            revWalk.dispose();

            StepStatus stepStatus = super.businessExecute();

            if (stepStatus.isSuccess()) {
                RevCommit commit = super.getCommit();
                this.getInspector().getGitHelper().computePatchStats(this.getInspector().getJobStatus(), git, headRev, commit);

                if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) {
                    this.setPushState(PushState.PATCH_COMMITTED);
                } else {
                    this.setPushState(PushState.REPAIR_INFO_COMMITTED);
                }
            } else {
                if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) {
                    this.setPushState(PushState.PATCH_NOT_COMMITTED);
                } else {
                    this.setPushState(PushState.REPAIR_INFO_NOT_COMMITTED);
                }
            }
            return stepStatus;
        } catch (IOException e) {
            this.addStepError("Error while opening the local git repository, maybe it has not been initialized.", e);
        }
        if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) {
            this.setPushState(PushState.PATCH_NOT_COMMITTED);
        } else {
            this.setPushState(PushState.REPAIR_INFO_NOT_COMMITTED);
        }
        return StepStatus.buildSkipped(this,"Error while committing.");
    } else {
        this.getLogger().info("Repairnator is configured NOT to push. Step bypassed.");
        return StepStatus.buildSkipped(this);
    }
}
 
Example 16
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath) throws IOException {
    Repository r = git.getRepository();
    String blobPath = trimLeadingSlash(pathOrBlobPath);

    RevCommit commit;
    if (Strings.isNotBlank(objectId)) {
        commit = CommitUtils.getCommit(r, objectId);
    } else {
        commit = CommitUtils.getHead(r);
    }
    RevCommit baseCommit = null;
    if (Strings.isNotBlank(baseObjectId) && !Objects.equals(baseObjectId, objectId)) {
        baseCommit = CommitUtils.getCommit(r, baseObjectId);
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    DiffFormatter formatter = createDiffFormatter(r, buffer);

    RevTree commitTree = commit.getTree();
    RevTree baseTree;
    if (baseCommit == null) {
        if (commit.getParentCount() > 0) {
            final RevWalk rw = new RevWalk(r);
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            rw.dispose();
            baseTree = parent.getTree();
        } else {
            // FIXME initial commit. no parent?!
            baseTree = commitTree;
        }
    } else {
        baseTree = baseCommit.getTree();
    }

    List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree);
    if (blobPath != null && blobPath.length() > 0) {
        for (DiffEntry diffEntry : diffEntries) {
            if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) {
                formatter.format(diffEntry);
                break;
            }
        }
    } else {
        formatter.format(diffEntries);
    }
    formatter.flush();
    return buffer.toString();
}
 
Example 17
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
public TestVersionResult determineVersions(final String fetchRevision) throws StoreException.ReadException {
    try {
        final RevWalk walk = new RevWalk(git.getRepository());
        final ObjectId commitId = ObjectId.fromString(fetchRevision);
        final RevCommit headTree = walk.parseCommit(commitId);
        final RevTree tree = headTree.getTree();

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        final TreeWalk treeWalk = new TreeWalk(git.getRepository());
        treeWalk.addTree(tree);
        treeWalk.setFilter(AndTreeFilter
            .create(PathFilter.create(testDefinitionsDirectory), PathSuffixFilter.create("definition.json")));
        treeWalk.setRecursive(true);

        final List<TestVersionResult.Test> tests = Lists.newArrayList();
        while (treeWalk.next()) {
            final ObjectId id = treeWalk.getObjectId(0);
            // final RevTree revTree = walk.lookupTree(id);

            final String path = treeWalk.getPathString();
            final String[] pieces = path.split("/");
            final String testname = pieces[pieces.length - 2]; // tree / parent directory name

            // testname, blobid pair
            // note this is the blobid hash - not a commit hash
            // RevTree.id and RevBlob.id
            tests.add(new TestVersionResult.Test(testname, id.name()));
        }

        walk.dispose();
        return new TestVersionResult(
                tests,
                new Date(Long.valueOf(headTree.getCommitTime()) * 1000 /* convert seconds to milliseconds */),
                determineAuthorId(headTree),
                headTree.toObjectId().getName(),
                headTree.getFullMessage()
        );
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}