Java Code Examples for org.eclipse.jgit.revwalk.RevCommit#getParents()

The following examples show how to use org.eclipse.jgit.revwalk.RevCommit#getParents() . 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: CommitUtil.java    From SZZUnleashed with MIT License 6 votes vote down vote up
/**
 * Parse the lines a commit recently made changes to compared to its parent.
 *
 * @param revc the current revision.
 * @return a commit object containing all differences.
 */
public Commit getCommitDiffingLines(RevCommit revc, RevCommit... revother)
    throws IOException, GitAPIException {

  if (revc.getId() == revc.zeroId()) return null;

  RevCommit parent = null;
  if (revother.length > 0) parent = revother[0];
  else if (revc.getParents().length > 0) parent = revc.getParent(0);
  else parent = revc;

  if (parent.getId() == ObjectId.zeroId()) return null;

  List<DiffEntry> diffEntries = diffRevisions(parent, revc);

  Commit commit = new Commit(revc);

  for (DiffEntry entry : diffEntries) {
    DiffLines changedLines = diffFile(entry);

    commit.diffWithParent.put(entry.getNewPath(), changedLines);
    commit.changeTypes.put(entry.getNewPath(), entry.getChangeType());
  }
  return commit;
}
 
Example 2
Source File: GitSCM.java    From repositoryminer with Apache License 2.0 6 votes vote down vote up
private Commit processCommit(RevCommit revCommit) {
	PersonIdent author = revCommit.getAuthorIdent();
	PersonIdent committer = revCommit.getCommitterIdent();

	Developer myAuthor = new Developer(author.getName(), author.getEmailAddress());
	Developer myCommitter = new Developer(committer.getName(), committer.getEmailAddress());

	List<String> parents = new ArrayList<String>();
	for (RevCommit parent : revCommit.getParents()) {
		parents.add(parent.getName());
	}

	List<Change> changes = null;
	try {
		changes = getChangesForCommitedFiles(revCommit.getName());
	} catch (IOException e) {
		close();
		throw new RepositoryMinerException(e);
	}

	return new Commit(null, revCommit.getName(), myAuthor, myCommitter, revCommit.getFullMessage().trim(), changes,
			parents, author.getWhen(), committer.getWhen(), (parents.size() > 1), null);
}
 
Example 3
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 6 votes vote down vote up
/**
 * Add a commit to all histories of all tests modified by this commit
 */
private void parseCommit(
        final RevCommit commit,
        final Map<String, List<Revision>> histories,
        final Set<ObjectId> visited,
        final Queue<RevCommit> queue
) throws IOException {
    if (!visited.add(commit.getId())) {
        return;
    }

    final Set<String> modifiedTests = getModifiedTests(commit);
    for (final String testName : modifiedTests) {
        final List<Revision> history = histories.computeIfAbsent(testName, x -> new ArrayList<>());
        history.add(createRevisionFromCommit(commit));
    }

    final RevCommit[] parents = commit.getParents();
    for (final RevCommit parent : parents) {
        queue.add(revWalk.parseCommit(parent.getId()));
    }
}
 
Example 4
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 6 votes vote down vote up
private Set<String> getModifiedTests(final RevCommit commit) throws IOException {
    final RevCommit[] parents = commit.getParents();
    final Set<String> result = new HashSet<>();
    if (parents.length == 1) { // merge commit if length > 1
        final RevCommit parent = revWalk.parseCommit(parents[0].getId());
        // get diff of this commit to its parent, as list of paths
        final List<DiffEntry> diffs = getDiffEntries(commit, parent);
        for (final DiffEntry diff : diffs) {
            final String changePath = diff.getChangeType().equals(DiffEntry.ChangeType.DELETE) ? diff.getOldPath() : diff.getNewPath();
            final Matcher testNameMatcher = testNamePattern.matcher(changePath);

            if (testNameMatcher.matches()) {
                final String testName = testNameMatcher.group(1);
                result.add(testName);
            }
        }
    }
    return result;
}
 
Example 5
Source File: GitUtils.java    From jphp with Apache License 2.0 6 votes vote down vote up
public static ArrayMemory valueOf(RevCommit value) {
    ArrayMemory memory = valueOf((RevObject) value);

    memory.refOfIndex("commitTime").assign(value.getCommitTime());
    memory.refOfIndex("encoding").assign(value.getEncodingName());
    memory.refOfIndex("shortMessage").assign(value.getShortMessage());
    memory.refOfIndex("fullMessage").assign(value.getFullMessage());
    
    ArrayMemory parents = new ArrayMemory();
    for (RevCommit revCommit : value.getParents()) {
        parents.add(valueOf((RevObject)revCommit));
    }

    memory.refOfIndex("parents").assign(parents);

    PersonIdent authorIdent = value.getAuthorIdent();
    memory.refOfIndex("author").assign(authorIdent == null ? Memory.NULL : valueOf(authorIdent));

    PersonIdent committerIdent = value.getCommitterIdent();
    memory.refOfIndex("committer").assign(committerIdent == null ? Memory.NULL : valueOf(committerIdent));

    return memory;
}
 
Example 6
Source File: PullRequest.java    From onedev with MIT License 5 votes vote down vote up
public ObjectId getComparisonOrigin(ObjectId comparisonBase) {
	if (contains(comparisonBase))
		return comparisonBase;
	
	RevCommit comparisonBaseCommit = getTargetProject().getRevCommit(comparisonBase, true);
	for (RevCommit parentCommit: comparisonBaseCommit.getParents()) {
		if (contains(parentCommit))
			return parentCommit.copy();
	}
	throw new IllegalStateException();
}
 
Example 7
Source File: RootCommit.java    From jgitver with Apache License 2.0 5 votes vote down vote up
static RevFilter rootFilter() {
    return new RevFilter() {
        @Override
        public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
            return commit.getParents().length == 0;
        }

        @Override
        public RevFilter clone() {
            return rootFilter();
        }
    };
}
 
Example 8
Source File: ExtractProjectCommitsAdapter.java    From coderadar with MIT License 5 votes vote down vote up
private List<Commit> getCommits(DateRange range, String repositoryRoot) {
  List<RevCommit> revCommits = RevCommitHelper.getRevCommits(repositoryRoot);

  int revCommitsSize = revCommits.size();
  HashMap<String, Commit> map = new HashMap<>(revCommitsSize);
  for (RevCommit rc : revCommits) {
    if (isInDateRange(range, rc)) {
      Commit commit = map.get(rc.getName());
      if (commit == null) {
        commit = mapRevCommitToCommit(rc);
      }
      List<Commit> parents =
          rc.getParentCount() > 0
              ? new ArrayList<>(rc.getParentCount())
              : Collections.emptyList();
      for (RevCommit parent : rc.getParents()) {
        if (isInDateRange(range, parent)) {
          Commit parentCommit = map.get(parent.getId().getName());
          if (parentCommit == null) {
            parentCommit = mapRevCommitToCommit(parent);
            map.put(parent.getName(), parentCommit);
          }
          parents.add(parentCommit);
        }
      }
      commit.setParents(parents);
      map.put(rc.getName(), commit);
    }
  }
  return new ArrayList<>(map.values());
}
 
Example 9
Source File: GitRepo.java    From git-changelog-lib with Apache License 2.0 5 votes vote down vote up
private Set<TraversalWork> populateCommitPerTag(
    final RevCommit from,
    final ObjectId to,
    final Map<String, Set<GitCommit>> commitsPerTagName,
    final Map<String, Ref> tagPerCommitHash,
    final Map<String, String> tagPerCommitsHash,
    final Map<String, Date> datePerTag,
    String currentTagName)
    throws Exception {
  final String thisCommitHash = to.getName();
  if (isMappedToAnotherTag(tagPerCommitsHash, thisCommitHash)) {
    return newTreeSet();
  }
  final RevCommit thisCommit = this.revWalk.lookupCommit(to);
  this.revWalk.parseHeaders(thisCommit);
  if (thisIsANewTag(tagPerCommitHash, thisCommitHash)) {
    currentTagName = getTagName(tagPerCommitHash, thisCommitHash);
  }
  if (currentTagName != null) {
    if (addCommitToCurrentTag(commitsPerTagName, currentTagName, thisCommit)) {
      datePerTag.put(currentTagName, new Date(thisCommit.getCommitTime() * 1000L));
    }
    noteThatTheCommitWasMapped(tagPerCommitsHash, currentTagName, thisCommitHash);
  }
  if (notFirstIncludedCommit(from, to)) {
    final Set<TraversalWork> work = newTreeSet();
    for (final RevCommit parent : thisCommit.getParents()) {
      if (shouldInclude(parent)) {
        work.add(new TraversalWork(parent, currentTagName));
      }
    }
    return work;
  }
  return newTreeSet();
}
 
Example 10
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<String> showRevision(ObjectId from, ObjectId to, Boolean useRawOutput) throws GitException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        w.markStart(w.parseCommit(to));
        if (from!=null)
            w.markUninteresting(w.parseCommit(from));
        else
            w.setRevFilter(MaxCountRevFilter.create(1));

        List<String> r = new ArrayList<>();
        StringWriter sw = new StringWriter();
        RawFormatter f = new RawFormatter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            for (RevCommit c : w) {
                // do not duplicate merge commits unless using raw output
                if (c.getParentCount()<=1 || !useRawOutput) {
                    f.format(c,null,pw,useRawOutput);
                } else {
                    // the effect of the -m option, which makes the diff produce for each parent of a merge commit
                    for (RevCommit p : c.getParents()) {
                        f.format(c,p,pw,useRawOutput);
                    }
                }

                r.addAll(Arrays.asList(sw.toString().split("\n")));
                sw.getBuffer().setLength(0);
            }
        }
        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example 11
Source File: DescribedTags.java    From gradle-gitsemver with Apache License 2.0 5 votes vote down vote up
public static TagVersionAndCount resolveLatestTagVersionAndCount(
        Repository repo, TagVersionAndCount curTag, int recur) throws IOException,
        RefNotFoundException, GitAPIException {
    Git git = new Git(repo);
    String described = git.describe().setTarget(curTag.getVersion()).call();
    if (described == null)
        return null;
    TagVersionAndCount describedTag = parseDescribeOutput(described);
    if (!SemanticVersions.isValid(GitRepos.stripVFromVersionString(describedTag.getVersion()))) {
        RevWalk revWalk = new RevWalk(repo);
        RevCommit describedRev = revWalk.parseCommit(repo.resolve(describedTag.getVersion()));
        TagVersionAndCount mostRecentParentTag = new TagVersionAndCount("", Integer.MAX_VALUE);
        for (RevCommit parent : describedRev.getParents()) {
            TagVersionAndCount parentTag = new TagVersionAndCount(parent.name(), -1);
            TagVersionAndCount resolvedParentTag = resolveLatestTagVersionAndCount(repo, parentTag, recur + 1);
            if (resolvedParentTag == null)
                continue;
            if (resolvedParentTag.getCount() < mostRecentParentTag.getCount()) {
                mostRecentParentTag = resolvedParentTag;
            }
        }
        if (mostRecentParentTag.getCount() == Integer.MAX_VALUE) {
            return null;
        }
        return mostRecentParentTag;
    } else {
    	if (recur != 0)
    		return new TagVersionAndCount(describedTag.getVersion(), -1);
        return describedTag;
    }
}
 
Example 12
Source File: DistanceCalculator.java    From jgitver with Apache License 2.0 4 votes vote down vote up
public Optional<Integer> distanceTo(ObjectId target) {
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit head = walk.parseCommit(startId);

        Deque<Pair<Integer, RevCommit>> parentsStack = new LinkedList<>();
        parentsStack.add(Pair.of(0, head));
        Set<RevCommit> processedRevs = new HashSet<>();

        int commitCount = 0;
        while (!parentsStack.isEmpty()) {
            // based on https://stackoverflow.com/questions/33038224/how-to-call-git-show-first-parent-in-jgit
            RevCommit[] parents = head.getParents();

            if (head.getId().getName().equals(target.getName())) {
                // we found it
                return Optional.of(Integer.valueOf(commitCount));
            }
            // get next head
            RevCommit firstParent = null;
            if (parents != null && parents.length > 0) {
                firstParent = parents[0];
            }
            if (firstParent != null && !processedRevs.contains(firstParent)) {
                // follow the first parent but only if not yet processed for faster processing and to avoid loops
                head = walk.parseCommit(firstParent);
                processedRevs.add(firstParent);
                // remember other parents as we may need to follow the other parents as well if
                // the target is not on the current branch.
                for (int i = 1; i < parents.length; i++) {
                    parentsStack.push(Pair.of(commitCount, parents[i]));
                }
            } else {
                // traverse next parent
                Pair<Integer, RevCommit> previous = parentsStack.poll();
                commitCount = previous.getLeft();
                RevCommit nextParent = previous.getRight();
                head = walk.parseCommit(nextParent);
                processedRevs.add(nextParent);
            }

            if (commitCount >= maxDepth) {
                return Optional.empty();
            }

            commitCount++;
        }
    } catch (IOException ignore) {
        ignore.printStackTrace();
    }
    return Optional.empty();
}
 
Example 13
Source File: LayoutHelper.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get new revisions list.
 *
 * @param repository    Repository.
 * @param loaded        Already loaded commits.
 * @param targetCommits Target commits.
 * @return Return new commits ordered by creation time. Parent revision always are before child.
 */
public static List<RevCommit> getNewRevisions(@NotNull Repository repository, @NotNull Set<? extends ObjectId> loaded, @NotNull Collection<? extends ObjectId> targetCommits) throws IOException {
  final Map<RevCommit, RevisionNode> revisionChilds = new HashMap<>();
  final Deque<RevCommit> revisionFirst = new ArrayDeque<>();
  final Deque<RevCommit> revisionQueue = new ArrayDeque<>();
  final RevWalk revWalk = new RevWalk(repository);
  for (ObjectId target : targetCommits) {
    if (!loaded.contains(target)) {
      final RevCommit revCommit = revWalk.parseCommit(target);
      revisionQueue.add(revCommit);
      revisionChilds.put(revCommit, new RevisionNode());
    }
  }
  while (!revisionQueue.isEmpty()) {
    final RevCommit commit = revWalk.parseCommit(revisionQueue.remove());
    if (commit == null || loaded.contains(commit.getId())) {
      revisionFirst.add(commit);
      continue;
    }
    if (commit.getParentCount() > 0) {
      final RevisionNode commitNode = revisionChilds.get(commit);
      for (RevCommit parent : commit.getParents()) {
        commitNode.parents.add(parent);
        revisionChilds.computeIfAbsent(parent, (id) -> {
          revisionQueue.add(parent);
          return new RevisionNode();
        }).childs.add(commit);
      }
    } else {
      revisionFirst.add(commit);
    }
  }
  final List<RevCommit> result = new ArrayList<>(revisionChilds.size());
  while (!revisionChilds.isEmpty()) {
    RevCommit firstCommit = null;
    RevisionNode firstNode = null;
    final Iterator<RevCommit> iterator = revisionFirst.iterator();
    while (iterator.hasNext()) {
      final RevCommit iterCommit = iterator.next();
      final RevisionNode iterNode = revisionChilds.get(iterCommit);
      if (iterNode == null) {
        iterator.remove();
        continue;
      }
      if (!iterNode.parents.isEmpty()) {
        iterator.remove();
      } else if (firstCommit == null || firstCommit.getCommitTime() > iterCommit.getCommitTime()) {
        firstNode = iterNode;
        firstCommit = iterCommit;
      }
    }
    if (firstNode == null || firstCommit == null) {
      throw new IllegalStateException();
    }
    revisionChilds.remove(firstCommit);
    result.add(firstCommit);
    for (RevCommit childId : firstNode.childs) {
      final RevisionNode childNode = revisionChilds.get(childId);
      if (childNode != null) {
        childNode.parents.remove(firstCommit);
        if (childNode.parents.isEmpty()) {
          revisionFirst.add(childId);
        }
      }
    }
  }
  return result;
}
 
Example 14
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
/**
 * Formats a commit into the raw format.
 *
 * @param commit
 *      Commit to format.
 * @param parent
 *      Optional parent commit to produce the diff against. This only matters
 *      for merge commits, and git-log/git-whatchanged/etc behaves differently with respect to this.
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE",
        justification = "Windows git implementation requires specific line termination")
void format(RevCommit commit, RevCommit parent, PrintWriter pw, Boolean useRawOutput) throws IOException {
    if (parent!=null)
        pw.printf("commit %s (from %s)\n", commit.name(), parent.name());
    else
        pw.printf("commit %s\n", commit.name());

    pw.printf("tree %s\n", commit.getTree().name());
    for (RevCommit p : commit.getParents())
        pw.printf("parent %s\n",p.name());
    FastDateFormat iso = FastDateFormat.getInstance(ISO_8601);
    PersonIdent a = commit.getAuthorIdent();
    pw.printf("author %s <%s> %s\n", a.getName(), a.getEmailAddress(), iso.format(a.getWhen()));
    PersonIdent c = commit.getCommitterIdent();
    pw.printf("committer %s <%s> %s\n", c.getName(), c.getEmailAddress(), iso.format(c.getWhen()));

    // indent commit messages by 4 chars
    String msg = commit.getFullMessage();
    if (msg.endsWith("\n")) msg=msg.substring(0,msg.length()-1);
    msg = msg.replace("\n","\n    ");
    msg="\n    "+msg+"\n";

    pw.println(msg);

    // see man git-diff-tree for the format
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         TreeWalk tw = new TreeWalk(or)) {
    if (parent != null) {
        /* Caller provided a parent commit, use it */
        tw.reset(parent.getTree(), commit.getTree());
    } else {
        if (commit.getParentCount() > 0) {
            /* Caller failed to provide parent, but a parent
             * is available, so use the parent in the walk
             */
            tw.reset(commit.getParent(0).getTree(), commit.getTree());
        } else {
            /* First commit in repo has 0 parent count, but
             * the TreeWalk requires exactly two nodes for its
             * walk.  Use the same node twice to satisfy
             * TreeWalk. See JENKINS-22343 for details.
             */
            tw.reset(commit.getTree(), commit.getTree());
        }
    }
    tw.setRecursive(true);
    tw.setFilter(TreeFilter.ANY_DIFF);

    final RenameDetector rd = new RenameDetector(repo);

    rd.reset();
    rd.addAll(DiffEntry.scan(tw));
    List<DiffEntry> diffs = rd.compute(or, null);
    if (useRawOutput) {
     for (DiffEntry diff : diffs) {
         pw.printf(":%06o %06o %s %s %s\t%s",
                 diff.getOldMode().getBits(),
                 diff.getNewMode().getBits(),
                 diff.getOldId().name(),
                 diff.getNewId().name(),
                 statusOf(diff),
                 diff.getChangeType()==ChangeType.ADD ? diff.getNewPath() : diff.getOldPath());

         if (hasNewPath(diff)) {
             pw.printf(" %s",diff.getNewPath()); // copied to
         }
         pw.println();
         pw.println();
     }
        }
    }
}