List of usage examples for org.eclipse.jgit.revwalk RevCommit getParent
public final RevCommit getParent(int nth)
From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java
License:Open Source License
private void processDiff(Repository repository, RevWalk walk, RevCommit current, DiffOutputStream outputStream, Map<String, FileStats> fileStatsMap) throws IOException { assert (repository != null); assert (walk != null); assert (current != null); assert (outputStream != null); assert (fileStatsMap != null); if (processDiffs == false) { return;/*from w w w . j a va 2 s .co m*/ } try { DiffFormatter df = new DiffFormatter(outputStream); df.setRepository(repository); df.setDetectRenames(true); List<DiffEntry> entries; if (current.getParentCount() > 0) { RevCommit parent = current.getParent(0); ObjectId oldTree = walk.parseCommit(parent).getTree(); ObjectId newTree = current.getTree(); entries = df.scan(oldTree, newTree); } else { entries = df.scan(new EmptyTreeIterator(), new CanonicalTreeParser(null, walk.getObjectReader(), current.getTree())); } for (DiffEntry de : entries) { if (stopped == true) { break; } int emptyLinesAddedStart = outputStream.getTotalEmptyLinesAdded(); int emptyLinesRemovedStart = outputStream.getTotalEmptyLinesRemoved(); int linesAddedStart = outputStream.getTotalLinesAdded(); int linesRemovedStart = outputStream.getTotalLinesRemoved(); int chunksStart = outputStream.getTotalChunks(); String oldPath = null; String path = null; switch (de.getChangeType()) { case ADD: path = de.getNewPath(); break; case DELETE: path = de.getOldPath(); break; case MODIFY: path = de.getOldPath(); break; case COPY: oldPath = de.getOldPath(); path = de.getNewPath(); break; case RENAME: oldPath = de.getOldPath(); path = de.getNewPath(); break; default: continue; } assert (fileStatsMap.containsKey(path) == false); assert (path != null); FileStats fileStats = new FileStats(); fileStatsMap.put(path, fileStats); outputStream.resetFile(); df.format(de); df.flush(); fileStats.emptyLinesAdded = outputStream.getTotalEmptyLinesAdded() - emptyLinesAddedStart; fileStats.emptyLinesRemoved = outputStream.getTotalEmptyLinesRemoved() - emptyLinesRemovedStart; fileStats.linesAdded += outputStream.getTotalLinesAdded() - linesAddedStart; fileStats.linesRemoved += outputStream.getTotalLinesRemoved() - linesRemovedStart; fileStats.chunks += outputStream.getTotalChunks() - chunksStart; fileStats.type = de.getChangeType(); fileStats.oldPath = oldPath; } } catch (IOException e) { throw e; } }
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}. * /*from www .j a va 2s . c om*/ * @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. * /* w w w. ja v a2 s. co m*/ * @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:boa.datagen.scm.GitCommit.java
License:Apache License
public void getChangeFiles(Map<String, Integer> revisionMap, RevCommit rc) { HashMap<String, String> rChangedPaths = new HashMap<String, String>(); HashMap<String, String> rRemovedPaths = new HashMap<String, String>(); HashMap<String, String> rAddedPaths = new HashMap<String, String>(); if (rc.getParentCount() == 0) getChangeFiles(null, rc, rChangedPaths, rRemovedPaths, rAddedPaths); else {/*from w ww. j a v a2 s.c om*/ int[] parentList = new int[rc.getParentCount()]; for (int i = 0; i < rc.getParentCount(); i++) { try { getChangeFiles(revwalk.parseCommit(rc.getParent(i).getId()), rc, rChangedPaths, rRemovedPaths, rAddedPaths); } catch (IOException e) { if (debug) System.err.println("Git Error parsing parent commit. " + e.getMessage()); } parentList[i] = revisionMap.get(rc.getParent(i).getName()); } setParentIndices(parentList); if (parentList.length > 1) { rChangedPaths.putAll(rAddedPaths); rChangedPaths.putAll(rRemovedPaths); for (String key : rChangedPaths.keySet()) rChangedPaths.put(key, key); rAddedPaths.clear(); rRemovedPaths.clear(); } } setChangedPaths(rChangedPaths); setRemovedPaths(rRemovedPaths); setAddedPaths(rAddedPaths); }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
@Override public Commit getCommit(String id) { Git git = null;/* w w w . java 2 s . co m*/ try { git = Git.open(new File(path)); Repository repo = git.getRepository(); Iterable<RevCommit> commits = git.log().add(repo.resolve(id)).call(); Commit theCommit = null; for (RevCommit jgitCommit : commits) { Developer author = new Developer(jgitCommit.getAuthorIdent().getName(), jgitCommit.getAuthorIdent().getEmailAddress()); Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(), jgitCommit.getCommitterIdent().getEmailAddress()); String msg = jgitCommit.getFullMessage().trim(); String hash = jgitCommit.getName().toString(); long epoch = jgitCommit.getCommitTime(); String parent = (jgitCommit.getParentCount() > 0) ? jgitCommit.getParent(0).getName().toString() : ""; GregorianCalendar date = new GregorianCalendar(); date.setTime(new Date(epoch * 1000L)); theCommit = new Commit(hash, author, committer, date, msg, parent); List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit); if (diffsForTheCommit.size() > MAX_NUMBER_OF_FILES_IN_A_COMMIT) { log.error("commit " + id + " has more than files than the limit"); throw new RuntimeException("commit " + id + " too big, sorry"); } for (DiffEntry diff : diffsForTheCommit) { ModificationType change = Enum.valueOf(ModificationType.class, diff.getChangeType().toString()); String oldPath = diff.getOldPath(); String newPath = diff.getNewPath(); String diffText = ""; String sc = ""; if (diff.getChangeType() != ChangeType.DELETE) { diffText = getDiffText(repo, diff); sc = getSourceCode(repo, diff); } if (diffText.length() > MAX_SIZE_OF_A_DIFF) { log.error("diff for " + newPath + " too big"); diffText = "-- TOO BIG --"; } theCommit.addModification(oldPath, newPath, change, diffText, sc); } break; } return theCommit; } catch (Exception e) { throw new RuntimeException("error detailing " + id + " in " + path, e); } finally { if (git != null) git.close(); } }
From source file:br.com.metricminer2.scm.GitRepository.java
License:Apache License
private List<DiffEntry> diffsForTheCommit(Repository repo, RevCommit commit) throws IOException, AmbiguousObjectException, IncorrectObjectTypeException { AnyObjectId currentCommit = repo.resolve(commit.getName()); AnyObjectId parentCommit = commit.getParentCount() > 0 ? repo.resolve(commit.getParent(0).getName()) : null; DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setBinaryFileThreshold(2 * 1024); // 2 mb max a file df.setRepository(repo);/*from w w w .j a v a 2 s . c om*/ df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = null; if (parentCommit == null) { RevWalk rw = new RevWalk(repo); diffs = df.scan(new EmptyTreeIterator(), new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree())); rw.release(); } else { diffs = df.scan(parentCommit, currentCommit); } df.release(); return diffs; }
From source file:br.com.riselabs.cotonet.builder.NetworkBuilder.java
License:Open Source License
/** * Returns the conflicting merge scenarios * /*from ww w . j a v a 2 s. c om*/ * @return - a list of merge scenarios. it may be empty in case of no * conflict. * @throws IOException */ private List<MergeScenario> getMergeScenarios() throws IOException { List<MergeScenario> result = new ArrayList<MergeScenario>(); List<RevCommit> mergeCommits = new ArrayList<RevCommit>(); Iterable<RevCommit> gitlog; try { Git git = Git.wrap(getProject().getRepository()); gitlog = git.log().call(); for (RevCommit commit : gitlog) { if (commit.getParentCount() == 2) { mergeCommits.add(commit); // collecting merge commits // we know there is only to parents RevCommit leftParent = commit.getParent(0); RevCommit rightParent = commit.getParent(1); ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(getProject().getRepository(), true); // selecting the conflicting ones boolean noConflicts = false; try { noConflicts = merger.merge(leftParent, rightParent); } catch (NoMergeBaseException e) { StringBuilder sb = new StringBuilder(); sb.append("[" + project.getName() + ":" + project.getUrl() + "] " + "Skipping merge scenario due to '" + e.getMessage() + "'\n"); sb.append("---> Skipped scenario:\n"); sb.append("::Base (<several>): \n"); sb.append("::Left (" + leftParent.getAuthorIdent().getWhen().toString() + "):" + leftParent.getName() + "\n"); sb.append("::Right (" + rightParent.getAuthorIdent().getWhen().toString() + "):" + rightParent.getName() + "\n"); Logger.log(log, sb.toString()); Logger.logStackTrace(log, e); continue; } if (noConflicts) { continue; } RevWalk walk = new RevWalk(getProject().getRepository()); // for merges without a base commit if (merger.getBaseCommitId() == null) continue; RevCommit baseCommit = walk.lookupCommit(merger.getBaseCommitId()); walk.close(); Timestamp mergeDate = new Timestamp(commit.getAuthorIdent().getWhen().getTime()); result.add(new MergeScenario(baseCommit, leftParent, rightParent, commit, mergeDate)); } } } catch (GitAPIException e) { Logger.logStackTrace(log, e); } return result; }
From source file:co.bledo.gitmin.servlet.Review.java
License:Apache License
public Response commit(Request req) throws IOException, GitAPIException { String repoName = req.getParam("repo", ""); String hash = req.getParam("hash", ""); Git git = Git.open(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName)); /*/*www. j a v a2 s . c om*/ ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); List<DiffEntry> diffTest = git.diff().setOutputStream(baos1) .setOldTree(getTreeIterator(git.getRepository(), hash)) .setNewTree(getTreeIterator(git.getRepository(), hash + "^")) .call(); System.out.println(baos1.toString()); */ RepositoryBuilder builder = new RepositoryBuilder(); Repository repo = builder.setGitDir(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName)) .readEnvironment().findGitDir().build(); RevWalk rw = new RevWalk(repo); ObjectId hashOid = repo.resolve(hash); RevCommit commit = rw.parseCommit(hashOid); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DiffFormatter df = new DiffFormatter(baos); df.setRepository(repo); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent, commit); List<CommitInfo> commitInfos = new ArrayList<CommitInfo>(); for (DiffEntry diff : diffs) { CommitInfo nfo = new CommitInfo(); df.format(diff); nfo.diff = baos.toString(); nfo.oldContents = getFileContent(repo, parent, diff.getOldPath()); nfo.newContents = getFileContent(repo, parent, diff.getNewPath()); nfo.newFile = diff.getNewPath(); nfo.oldFile = diff.getOldPath(); commitInfos.add(nfo); } VelocityResponse resp = VelocityResponse.newInstance(req, this); resp.assign("nfolist", commitInfos); return log.exit(resp); }
From source file:com.amd.gerrit.plugins.manifestsubscription.Utilities.java
License:Open Source License
static ObjectId updateManifest(GitRepositoryManager gitRepoManager, MetaDataUpdate.Server metaDataUpdateFactory, ChangeHooks changeHooks, String projectName, String refName, Manifest manifest, String manifestSrc, String extraCommitMsg, String defaultBranchBase) throws JAXBException, IOException { Project.NameKey p = new Project.NameKey(projectName); Repository repo = gitRepoManager.openRepository(p); MetaDataUpdate update = metaDataUpdateFactory.create(p); ObjectId commitId = repo.resolve(refName); VersionedManifests vManifests = new VersionedManifests(refName); //TODO find a better way to detect no branch boolean refExists = true; try {// www. j a v a 2s. c o m vManifests.load(update, commitId); } catch (Exception e) { refExists = false; } RevCommit commit = null; if (refExists) { Map<String, Manifest> entry = Maps.newHashMapWithExpectedSize(1); entry.put("default.xml", manifest); vManifests.setManifests(entry); vManifests.setSrcManifestRepo(manifestSrc); vManifests.setExtraCommitMsg(extraCommitMsg); commit = vManifests.commit(update); } else { if (defaultBranchBase == null) defaultBranchBase = "refs/heads/master"; vManifests = new VersionedManifests(defaultBranchBase); ObjectId cid = repo.resolve(defaultBranchBase); try { vManifests.load(update, cid); } catch (ConfigInvalidException e) { e.printStackTrace(); } Map<String, Manifest> entry = Maps.newHashMapWithExpectedSize(1); entry.put("default.xml", manifest); vManifests.setManifests(entry); commit = vManifests.commitToNewRef(update, refName); } // TODO this may be bug in the MetaDataUpdate or VersionedMetaData // May be related: // https://code.google.com/p/gerrit/issues/detail?id=2564 // https://gerrit-review.googlesource.com/55540 if (commit != null) { ObjectId parent = ObjectId.zeroId(); if (commit.getParents().length > 0) { parent = commit.getParent(0).getId(); } changeHooks.doRefUpdatedHook(new Branch.NameKey(p, refName), parent, commit.getId(), null); return commit.getId(); } else { log.warn("Failing to commit manifest subscription update:" + "\n\tProject: " + projectName + "\n\tRef: " + refName); } return null; }
From source file:com.chungkwong.jgitgui.CommitTreeItem.java
License:Open Source License
@Override public Node getContentPage() { RevCommit rev = (RevCommit) getValue(); Repository repository = ((Git) getParent().getParent().getValue()).getRepository(); SplitPane page = new SplitPane(); page.setOrientation(Orientation.VERTICAL); StringBuilder buf = new StringBuilder(); buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PARENTS:")); for (int i = 0; i < rev.getParentCount(); i++) buf.append(rev.getParent(i)).append('\n'); buf.append(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("MESSAGE:")); buf.append(rev.getFullMessage());// w w w . j a va2 s .c om TextArea msg = new TextArea(buf.toString()); msg.setEditable(false); page.getItems().add(msg); SplitPane fileViewer = new SplitPane(); fileViewer.setOrientation(Orientation.HORIZONTAL); TreeView tree = new TreeView(new TreeItem()); tree.setShowRoot(false); TextArea content = new TextArea(); content.setEditable(false); try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(rev.getTree()); walk.setRecursive(true); LinkedList<TreeItem> items = new LinkedList<>(); items.add(tree.getRoot()); while (walk.next()) { TreeItem item = new FileTreeItem(walk.getObjectId(0), walk.getPathString()); /*while(walk.getDepth()<items.size()-1) items.removeLast(); if(walk.getDepth()>items.size()-1) items.addLast(item);*/ items.getLast().getChildren().add(item); } } catch (Exception ex) { Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } tree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { if (t1 != null) { try { ObjectLoader obj = repository.open(((FileTreeItem) t1).getId()); if (obj.getType() != Constants.OBJ_TREE) { StringBuilder buf = new StringBuilder(); BufferedReader in = new BufferedReader( new InputStreamReader(obj.openStream(), rev.getEncoding())); content.setText(in.lines().collect(Collectors.joining("\n"))); } } catch (Exception ex) { Logger.getLogger(CommitTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } } } }); fileViewer.getItems().add(tree); fileViewer.getItems().add(content); page.getItems().add(fileViewer); page.setDividerPositions(0.2, 0.8); return page; }