List of usage examples for org.eclipse.jgit.revwalk RevCommit getParentCount
public final int getParentCount()
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 ww . ja v a 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: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 {// w w w .j av a 2 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;/*ww w. j a v a2 s . c om*/ 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);/* ww w .jav a 2 s. c o m*/ 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 * /* ww w . j a v a 2 s . c o m*/ * @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:br.edu.ifpb.scm.api.git.Git.java
/** * Cria um objeto verso/*from w w w . j ava 2s . c o m*/ * * @param repo {@link org.eclipse.jgit.lib.Repository} JGit * @param it RevCommit JGit * @return {@link Version} Verso */ private Version createVersion(RevCommit it) throws IOException { List<ChangedFiles> listOfChangedFiles = getChangedFilesFromSpecifiedVersion(extractHashFromCommit(it)); List<DiffEntry> listOfDiffs = Collections.EMPTY_LIST; boolean flag = false; if (it.getParentCount() <= 0) { flag = true; listOfDiffs = getDiff(extractHashFromCommit(it), flag); } listOfDiffs = getDiff(extractHashFromCommit(it), flag); return new Version(extractLocalDateFromCommit(it), extractHashFromCommit(it), it.getShortMessage(), listOfDiffs, createAuthor(it)); // .setChanges(listOfChangedFiles); }
From source file:br.edu.ifpb.scm.api.git.Git.java
/** * Recupera a referencia do RevCommit//from ww w . jav a2 s. c o m * * @param repoJGit {@link org.eclipse.jgit.lib.Repository} Repositorio JGit * @param commit String * @return List {@link List} de de {@link ChangedFiles} */ private List<ChangedFiles> getChangedFilesFromSpecifiedVersion(String commit) { RevCommit revCommit1 = convertStringToRevCommit(commit); //Fluxo alternativo quando chegar no primeiro commit do repositrio if (revCommit1.getParentCount() <= 0) { return searchDiff(revCommit1, revCommit1); } //trocado pela chamada de metodos RevCommit revCommit2 = convertStringToRevCommit(revCommit1.getParents()[0].getName()); return searchDiff(revCommit1, revCommit2); }
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());// ww w .jav a 2 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; }
From source file:com.gitblit.git.GitblitReceivePack.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. *///from ww w . j a v a 2s .c o m @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (commands.size() == 0) { // no receive commands to process // this can happen if receive pack subclasses intercept and filter // the commands LOGGER.debug("skipping pre-receive processing, no refs created, updated, or removed"); return; } if (repository.isMirror) { // repository is a mirror for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is a mirror!", repository.name); } return; } if (repository.isFrozen) { // repository is frozen/readonly for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); } return; } if (!repository.isBare) { // repository has a working copy for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); } return; } if (!canPush(commands)) { // user does not have push permissions for (ReceiveCommand cmd : commands) { sendRejection(cmd, "User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // reject the push because the pushing account does not have an email address for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Sorry, the account \"{0}\" does not have an email address set for committer verification!", user.username); } return; } // Optionally enforce that the committer of first parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain first parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String firstParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (firstParent != null) { if (!commit.getName().equals(firstParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { firstParent = null; } else { firstParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { // verification failed String reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); LOGGER.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { LOGGER.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: // reset branch commit cache on REWIND and DELETE CommitCache.instance().clear(repository.name, ref); break; default: break; } } else if (ref.equals(BranchTicketService.BRANCH)) { // ensure pushing user is an administrator OR an owner // i.e. prevent ticket tampering boolean permitted = user.canAdmin() || repository.isOwner(user.username); if (!permitted) { sendRejection(cmd, "{0} is not permitted to push to {1}", user.username, ref); } } else if (ref.startsWith(Constants.R_FOR)) { // prevent accidental push to refs/for sendRejection(cmd, "{0} is not configured to receive patchsets", repository.name); } } // call pre-receive plugins for (ReceiveHook hook : gitblit.getExtensions(ReceiveHook.class)) { try { hook.onPreReceive(this, commands); } catch (Exception e) { LOGGER.error("Failed to execute extension", e); } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(gitblit.getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(commands, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { LOGGER.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }
From source file:com.gitblit.git.ReceiveHook.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. *///from ww w. ja va2 s. c o m @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (repository.isFrozen) { // repository is frozen/readonly String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!repository.isBare) { // repository has a working copy String reason = MessageFormat.format( "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!user.canPush(repository)) { // user does not have push permissions String reason = MessageFormat.format("User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // emit warning if user does not have an email address logger.warn(MessageFormat.format( "Consider setting an email address for {0} ({1}) to improve committer verification.", user.getDisplayName(), user.username)); } // Optionally enforce that the committer of the left parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain of left parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String linearParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (linearParent != null) { if (!commit.getName().equals(linearParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { linearParent = null; } else { linearParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { String reason; if (StringUtils.isEmpty(user.emailAddress)) { // account does not have an email address reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4})", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username); } else { // account has an email address reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); } logger.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { logger.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } // reset branch commit cache on REWIND and DELETE for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: CommitCache.instance().clear(repository.name, ref); break; default: break; } } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(GitBlit.self().getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(repository, user, commands, rp, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { logger.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }