List of usage examples for org.eclipse.jgit.revwalk RevWalk RevWalk
public RevWalk(ObjectReader or)
From source file:ShowFileDiff.java
License:Apache License
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException, MissingObjectException, IncorrectObjectTypeException { // from the commit we can build the tree which allows us to construct the TreeParser 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(); try {/*from w w w . java 2 s .co m*/ oldTreeParser.reset(oldReader, tree.getId()); } finally { oldReader.release(); } walk.dispose(); return oldTreeParser; }
From source file:MyDiffFormatter.java
License:Eclipse Distribution License
/** * Determine the differences between two trees. * <p/>//from w w w. ja va 2 s. com * No output is created, instead only the file paths that are different are * returned. Callers may choose to format these paths themselves, or convert * them into {@link FileHeader} instances with a complete edit list by * <p/> * Either side may be null to indicate that the tree has beed added or * removed. The diff will be computed against nothing. * * @param a the old (or previous) side or null * @param b the new (or updated) side or null * @return the paths that are different. * @throws IOException trees cannot be read or file contents cannot be read. */ public List<DiffEntry> scan(AnyObjectId a, AnyObjectId b) throws IOException { assertHaveRepository(); RevWalk rw = new RevWalk(reader); RevTree aTree = a != null ? rw.parseTree(a) : null; RevTree bTree = b != null ? rw.parseTree(b) : null; return scan(aTree, bTree); }
From source file:actors.PostReceiveActor.java
License:Apache License
protected Collection<? extends RevCommit> parseCommitsFrom(ReceiveCommand command, Project project) { Repository repository = GitRepository.buildGitRepository(project); List<RevCommit> list = new ArrayList<>(); try {// w w w. j a va 2 s .c om ObjectId endRange = command.getNewId(); ObjectId startRange = command.getOldId(); RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(endRange)); if (startRange.equals(ObjectId.zeroId())) { // maybe this is a tag or an orphan branch list.add(rw.parseCommit(endRange)); rw.dispose(); return list; } else { rw.markUninteresting(rw.parseCommit(startRange)); } for (RevCommit rev : rw) { list.add(rev); } rw.dispose(); } catch (IOException e) { e.printStackTrace(); } return list; }
From source file:am.ik.categolj3.api.git.GitStore.java
License:Apache License
void syncHead() { log.info("Syncing HEAD..."); ObjectId oldHead = this.currentHead.get(); ObjectId newHead = this.head(); try (Repository repository = this.git.getRepository()) { DiffFormatter diffFormatter = new DiffFormatter(System.out); diffFormatter.setRepository(repository); RevWalk walk = new RevWalk(repository); try {/*from w w w . j a v a 2 s . c om*/ RevCommit fromCommit = walk.parseCommit(oldHead); RevCommit toCommit = walk.parseCommit(newHead); List<DiffEntry> list = diffFormatter.scan(fromCommit.getTree(), toCommit.getTree()); list.forEach(diff -> { log.info("[{}]\tnew={}\told={}", diff.getChangeType(), diff.getNewPath(), diff.getOldPath()); if (diff.getOldPath() != null) { Path path = Paths .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getOldPath()); if (Entry.isPublic(path)) { Long entryId = Entry.parseEntryId(path); log.info("evict Entry({})", entryId); this.entryCache.evict(entryId); } } if (diff.getNewPath() != null) { Path path = Paths .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getNewPath()); this.loadEntry(path).ifPresent(entry -> { log.info("put Entry({})", entry.getEntryId()); this.entryCache.put(entry.getEntryId(), entry); }); } }); } finally { walk.dispose(); } } catch (IOException e) { throw new UncheckedIOException(e); } catch (Exception e) { throw new IllegalStateException(e); } this.currentHead.set(newHead); }
From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java
License:Open Source License
private void _run() throws IOException, MinerException, SQLException { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(new File(settings.srcLocalPath, ".git")).readEnvironment() .findGitDir().build();//from ww w . j a v a 2 s . c o m /* Map<String,Ref> refs = repository.getAllRefs(); for (Map.Entry<String, Ref> ref : refs.entrySet ()) { System.out.println (ref.getKey ()); } */ Ref head = repository.getRef(startRef); if (head == null) { throw new MinerException("Unknown reference: '" + startRef + "'"); } RevWalk walk = new RevWalk(repository); RevCommit commit = walk.parseCommit(head.getObjectId()); walk.markStart(commit); walk.sort(RevSort.REVERSE); // count commit: (fast) int commitCount = 0; Iterator<RevCommit> iter = walk.iterator(); while (iter.hasNext()) { iter.next(); commitCount++; } emitTasksTotal(commitCount); // process commits: (slow) walk.reset(); walk.markStart(commit); walk.sort(RevSort.REVERSE); Map<String, ManagedFile> fileCache = new HashMap<String, ManagedFile>(); for (RevCommit rev : walk) { if (stopped == true) { break; } processCommit(repository, walk, rev, fileCache); } walk.dispose(); repository.close(); }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@SuppressWarnings("restriction") @Override/*from w w w. j a v a 2s.c om*/ public List<IReviewDescriptor> getReviews(URI uri) throws InvalidReviewRepositoryException { List<IReviewDescriptor> changeIds = new LinkedList<>(); try { // connect to the local git repository Git git = Git.open(new File(uri)); try { // Assume that origin refers to the remote gerrit repository // list all remote refs from origin Collection<Ref> remoteRefs = git.lsRemote().setTimeout(60).call(); Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN); // search for change refs for (Ref ref : remoteRefs) { Matcher matcher = changeRefPattern.matcher(ref.getName()); if (matcher.matches()) { String changePk = matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK); String changeId = "<unknown>"; GerritReviewDescriptor reviewDescriptor; try { reviewDescriptor = new GerritReviewDescriptor(Integer.parseInt(changePk), changeId); } catch (NumberFormatException nfe) { // FIXME ignore it or throw an exception? break; } if (!changeIds.contains(reviewDescriptor)) { changeIds.add(reviewDescriptor); /* * the change id is present in all commit messages, * so we extract it from the commit message of the * current ref */ FetchResult fetchResult = git.fetch().setRefSpecs(new RefSpec(ref.getName())).call(); Ref localRef = fetchResult.getAdvertisedRef(ref.getName()); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(localRef.getObjectId()); String[] paragraphs = commit.getFullMessage().split("\n"); String lastParagraph = paragraphs[paragraphs.length - 1]; Pattern pattern = Pattern.compile(".*Change-Id: (I[^ \n]*).*"); Matcher changeIdMatcher = pattern.matcher(lastParagraph); if (changeIdMatcher.matches()) { changeId = changeIdMatcher.group(1); reviewDescriptor.setChangeId(changeId); ; } else { logger.warn(MessageFormat.format( "Could not find the change id for Gerrit change with primary key {0}", changePk)); } revWalk.close(); } } } } catch (GitAPIException e) { throw new RepositoryIOException("Error during loading all remote changes", e); } } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } return changeIds; }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all involved models and diagrams for the given patchSet using the * given {@link Git} instance from the given git {@link Ref}. * // w w w.j a va 2s . c o m * @param patchSet * the patch set instance to store the involved models into * @param ref * the git ref to the commit which contains the patch set. * @param git * the git instance to use * @return a list containing the resource sets for the old and the new model * resources. * @throws IOException */ private List<ResourceSet> loadInvolvedModelsAndDiagrams(PatchSet patchSet, Ref ref, Git git) throws IOException { String commitHash = ref.getObjectId().name(); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); revWalk.close(); String parentCommitHash = oldCommit.getId().name(); URI repoURI = git.getRepository().getDirectory().toURI(); String authority = repoURI.getAuthority(); String path = repoURI.getPath(); String repoPath = (authority != null ? authority + "/" : "") + (path != null ? path : ""); if (repoPath.endsWith("/")) { repoPath = repoPath.substring(0, repoPath.length() - 1); } ResourceSet newResourceSet = createGitAwareResourceSet(commitHash, repoPath, Collections.<ResourceSet>emptyList()); ResourceSet oldModelResourceSet = createGitAwareResourceSet(parentCommitHash, repoPath, Collections.<ResourceSet>emptyList()); for (Patch patch : patchSet.getPatches()) { if (patch instanceof ModelPatch || patch instanceof DiagramPatch) { org.eclipse.emf.common.util.URI newUri = org.eclipse.emf.common.util.URI .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/" + patch.getNewPath()); org.eclipse.emf.common.util.URI oldUri = org.eclipse.emf.common.util.URI .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + parentCommitHash + "/" + patch.getOldPath()); if (patch.getChangeType() != PatchChangeType.DELETE) { // if the patch has been deleted no new resource exists Resource newResource = newResourceSet.getResource(newUri, true); try { applyResourceContent(newResource, patch, false); } catch (IOException e) { throw new IOException( MessageFormat.format("Could not load resource \"{0}\" for patch set {1}", newUri.toString(), patchSet.getId()), e); } } if (patch.getChangeType() != PatchChangeType.ADD) { // if the patch has been added no old resource exists Resource oldResource = oldModelResourceSet.getResource(oldUri, true); try { applyResourceContent(oldResource, patch, true); } catch (IOException e) { throw new IOException( MessageFormat.format("Could not load resource \"{0}\" for patch set {1}", oldUri.toString(), patchSet.getId()), e); } } } } List<ResourceSet> resourceSets = new ArrayList<>(2); resourceSets.add(oldModelResourceSet); resourceSets.add(newResourceSet); return resourceSets; }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all patches of from the given list of {@link DiffEntry}s. * /*from ww w. j a v a 2 s.com*/ * @param patchSet * the patchSet to add the patches to. * @param ref * the ref to the commit of the patch set. * @param repository * the git repository instance * @throws RepositoryIOException */ private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException { EList<Patch> patches = patchSet.getPatches(); Repository repository = git.getRepository(); try { RevWalk revWalk = new RevWalk(repository); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); ObjectReader objectReader = repository.newObjectReader(); revWalk.close(); CanonicalTreeParser newTreeIterator = new CanonicalTreeParser(); newTreeIterator.reset(objectReader, newCommit.getTree().getId()); CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser(); oldTreeIterator.reset(objectReader, oldCommit.getTree().getId()); List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call(); for (DiffEntry diff : diffs) { String newPath = diff.getNewPath(); String oldPath = diff.getOldPath(); Patch patch = null; /* * only papyrus diagrams are supported for now, so models are in * .uml files, diagrams in .notation files */ if (diff.getChangeType() != ChangeType.DELETE) { if (newPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (newPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } else { if (oldPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (oldPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } switch (diff.getChangeType()) { case ADD: patch.setChangeType(PatchChangeType.ADD); break; case COPY: patch.setChangeType(PatchChangeType.COPY); break; case DELETE: patch.setChangeType(PatchChangeType.DELETE); break; case MODIFY: patch.setChangeType(PatchChangeType.MODIFY); break; case RENAME: patch.setChangeType(PatchChangeType.RENAME); break; } patch.setNewPath(newPath); patch.setOldPath(oldPath); if (diff.getChangeType() != ChangeType.DELETE) { ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId()); patch.setNewContent(objectLoader.getBytes()); } if (diff.getChangeType() != ChangeType.ADD) { ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId()); patch.setOldContent(objectLoader.getBytes()); } patches.add(patch); } } catch (IOException e) { throw new RepositoryIOException(MessageFormat.format( "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } catch (GitAPIException e) { throw new RepositoryIOException( MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@Override public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor) throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException { monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN); String repoFileURI = COMMENTS_FILE_URI; try {/*from www .j a v a 2 s .c o m*/ Git git = Git.open(new File(uri)); Repository repository = git.getRepository(); ObjectInserter objectInserter = repository.newObjectInserter(); String commentRefName = getCommentRefName(modelReview); Ref commentRef = repository.exactRef(commentRefName); DirCache index = DirCache.newInCore(); DirCacheBuilder dirCacheBuilder = index.builder(); monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN); if (commentRef != null) { /* * The ref already exists so we have to copy the previous * RevTree to keep all already attached files */ RevWalk revWalk = new RevWalk(repository); RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId()); RevTree tree = prevCommit.getTree(); List<String> ignoredFiles = new ArrayList<>(); /* * add file path of the new file to the ignored file paths, as * we don't want any already existing old file in our new tree */ ignoredFiles.add(repoFileURI); buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles); revWalk.close(); } monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI)); addCommentsToResource(modelReview, resource); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resource.save(outputStream, null); // insert file as object byte[] content = outputStream.toByteArray(); long length = content.length; InputStream inputStream = new ByteArrayInputStream(content); ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream); inputStream.close(); // create tree entry DirCacheEntry entry = new DirCacheEntry(repoFileURI); entry.setFileMode(FileMode.REGULAR_FILE); entry.setLastModified(System.currentTimeMillis()); entry.setLength(length); entry.setObjectId(objectId); dirCacheBuilder.add(entry); dirCacheBuilder.finish(); // write new tree in database ObjectId indexTreeId = index.writeTree(objectInserter); monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN); // create commit CommitBuilder commitBuilder = new CommitBuilder(); PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview"); commitBuilder.setCommitter(personIdent); commitBuilder.setAuthor(personIdent); commitBuilder.setMessage( MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName())); if (commentRef != null) { commitBuilder.setParentId(commentRef.getObjectId()); } commitBuilder.setTreeId(indexTreeId); // commit ObjectId commitId = objectInserter.insert(commitBuilder); objectInserter.flush(); RefUpdate refUpdate = repository.updateRef(commentRefName); refUpdate.setNewObjectId(commitId); if (commentRef != null) refUpdate.setExpectedOldObjectId(commentRef.getObjectId()); else refUpdate.setExpectedOldObjectId(ObjectId.zeroId()); /* * TODO the result handling below is copied from the CommitCommand * class, I don't know if this is really necessary in our case */ Result result = refUpdate.forceUpdate(); switch (result) { case NEW: case FORCED: case FAST_FORWARD: { if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) { /* * Commit was successful. Now delete the files used for * merge commits */ repository.writeMergeCommitMsg(null); repository.writeMergeHeads(null); } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeCherryPickHead(null); } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeRevertHead(null); } break; } case REJECTED: case LOCK_FAILURE: throw new RepositoryIOException("Error occured during writing to the git repository", new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(), refUpdate.getRef(), result)); default: throw new RepositoryIOException("Error occured during writing to the git repository", new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, refUpdate.getRef().getName(), commitId.toString(), result))); } } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } finally { monitor.done(); } }
From source file:at.bitandart.zoubek.mervin.gerrit.GitURIParser.java
License:Open Source License
/** * loads the referenced commit//from www.ja v a 2 s.com * * @throws IOException * if an error occurs during parsing the URI */ private void loadCommit() throws IOException { if (repository == null) loadRepository(); RevWalk revWalk = new RevWalk(repository); commit = revWalk.parseCommit(ObjectId.fromString(commitHash)); revWalk.close(); }