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

The following examples show how to use org.eclipse.jgit.revwalk.RevCommit#getCommitTime() . 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: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the chronologically-last commit from a set of review comments.
 */
private RevCommit findLastCommitInComments(
    Collection<ReviewComment> collection, RevCommit defaultCommit)
    throws MissingObjectException, IncorrectObjectTypeException, IOException {
  RevCommit lastCommit = defaultCommit;
  for (ReviewComment comment : collection) {
    if (comment.getLocation() == null || comment.getLocation().getCommit() == null
        || comment.getLocation().getCommit().isEmpty()) {
      continue;
    }
    RevCommit currentCommit = resolveRevCommit(comment.getLocation().getCommit());
    if (currentCommit != null && currentCommit.getCommitTime() > lastCommit.getCommitTime()) {
      lastCommit = currentCommit;
    }
  }
  return lastCommit;
}
 
Example 2
Source File: GitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String noteId,
                           String notePath,
                           String commitMessage,
                           AuthenticationInfo subject) throws IOException {
  String noteFileName = buildNoteFileName(noteId, notePath);
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    boolean modified = gitDiff.parallelStream().anyMatch(diffEntry -> diffEntry.getNewPath().equals(noteFileName));
    if (modified) {
      LOGGER.debug("Changes found for pattern '{}': {}", noteFileName, gitDiff);
      DirCache added = git.add().addFilepattern(noteFileName).call();
      LOGGER.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOGGER.debug("No changes found {}", noteFileName);
    }
  } catch (GitAPIException e) {
    LOGGER.error("Failed to add+commit {} to Git", noteFileName, e);
  }
  return revision;
}
 
Example 3
Source File: Project.java    From onedev with MIT License 6 votes vote down vote up
public RevCommit getLastCommit() {
	if (lastCommitHolder == null) {
		RevCommit lastCommit = null;
		try {
			for (Ref ref: getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)) {
				RevCommit commit = getRevCommit(ref.getObjectId(), false);
				if (commit != null) {
					if (lastCommit != null) {
						if (commit.getCommitTime() > lastCommit.getCommitTime())
							lastCommit = commit;
					} else {
						lastCommit = commit;
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		lastCommitHolder = Optional.fromNullable(lastCommit);
	}
	return lastCommitHolder.orNull();
}
 
Example 4
Source File: OldGitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String pattern, String commitMessage, AuthenticationInfo subject) {
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    if (!gitDiff.isEmpty()) {
      LOG.debug("Changes found for pattern '{}': {}", pattern, gitDiff);
      DirCache added = git.add().addFilepattern(pattern).call();
      LOG.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOG.debug("No changes found {}", pattern);
    }
  } catch (GitAPIException e) {
    LOG.error("Failed to add+commit {} to Git", pattern, e);
  }
  return revision;
}
 
Example 5
Source File: Utils.java    From data7 with Apache License 2.0 5 votes vote down vote up
/**
 * Function to generate a commit Object from a revcommit object
 * @param git git repository
 * @param commit to generate the commit object from
 * @param filter whether of not files should be filtered
 * @return a commit object
 * @see Commit
 */
public static Commit generateCommitOfInterest(GitActions git, RevCommit commit,boolean filter) {
    try {
        String hash = commit.getName();
        String commitMessage = commit.getFullMessage();
        int timestamp = commit.getCommitTime();
        List<String> modifiedFiles = git.getListOfModifiedFile(commit.getName(), FILE_EXTENSION);
        List<FileFix> fixes = new ArrayList<>();
        for (String modifiedFile : modifiedFiles) {
            if (!filter || !modifiedFile.toLowerCase().contains("test")) {
                String newName = modifiedFile;
                GitActions.NamedCommit previousCommit = git.previousCommitImpactingAFile(modifiedFile, hash);
                String oldname = previousCommit.getFilePath();
                String oldHash = previousCommit.getRevCommit().getName();
                String oldContent = git.retrievingFileFromSpecificCommit(oldHash, oldname);
                String newContent = git.retrievingFileFromSpecificCommit(hash, newName);
                FileInterest old = new FileInterest(oldContent, oldname);
                FileInterest newer = new FileInterest(newContent, newName);
                fixes.add(new FileFix(old, newer, oldHash, git.getTimeCommit(oldHash)));
            }
        }
        return new Commit(hash, commitMessage, timestamp, fixes);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }
}
 
Example 6
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 5 votes vote down vote up
static Revision createRevisionFromCommit(final RevCommit commit) {
    return new Revision(
            commit.getName(),
            determineAuthorId(commit),
            new Date((long) commit.getCommitTime() * 1000 /* convert seconds to milliseconds */),
            commit.getFullMessage()
    );
}
 
Example 7
Source File: GitRepo.java    From git-changelog-lib with Apache License 2.0 5 votes vote down vote up
private GitCommit toGitCommit(final RevCommit revCommit) {
  final Boolean merge = revCommit.getParentCount() > 1;
  return new GitCommit( //
      revCommit.getAuthorIdent().getName(), //
      revCommit.getAuthorIdent().getEmailAddress(), //
      new Date(revCommit.getCommitTime() * 1000L), //
      revCommit.getFullMessage(), //
      revCommit.getId().getName(), //
      merge);
}
 
Example 8
Source File: GitCommit.java    From app-runner with MIT License 5 votes vote down vote up
public static GitCommit fromHEAD(Git git) throws Exception {
    ObjectId head = git.getRepository().resolve("HEAD");
    if (head != null) {
        RevCommit mostRecentCommit;
        try (RevWalk walk = new RevWalk(git.getRepository())) {
            mostRecentCommit = walk.parseCommit(head);
        }
        Date commitDate = new Date(1000L * mostRecentCommit.getCommitTime());
        String id = mostRecentCommit.getId().name();
        PersonIdent author = mostRecentCommit.getAuthorIdent();
        return new GitCommit(id, commitDate, author.getName(), mostRecentCommit.getFullMessage());
    } else {
        return null;
    }
}
 
Example 9
Source File: GitMigrator.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private Node createSaveSetNode(Node parentNode, FilePair filePair){
    Node saveSetNode = null;
    try {
        List<RevCommit> commits = findCommitsFor(filePair.bms);
        // Only latest commit considered for bms files
        RevCommit commit = commits.get(0);
        String author = commit.getAuthorIdent().getName();
        String commitMessage = commit.getFullMessage();
        Date commitDate = new Date(commit.getCommitTime() * 1000L);
        Map<String, String> properties = new HashMap<>();
        properties.put("description", commitMessage);
        saveSetNode = Node.builder()
                .name(filePair.bms.substring(filePair.bms.lastIndexOf("/") + 1))
                .nodeType(NodeType.CONFIGURATION)
                .userName(author)
                .created(commitDate)
                .lastModified(commitDate)
                .properties(properties)
                .build();
        saveSetNode =  saveAndRestoreService.createNode(parentNode.getUniqueId(), saveSetNode);
        String fullPath = gitRoot.getAbsolutePath() + "/" + filePair.bms;
        List<ConfigPv> configPvs = FileReaderHelper.readSaveSet(new FileInputStream(fullPath));
        saveAndRestoreService.updateSaveSet(saveSetNode, configPvs);
        createSnapshots(saveSetNode, filePair.snp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return saveSetNode;
}
 
Example 10
Source File: Tag.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@PropertyDescription(name = ProtocolConstants.KEY_LOCAL_TIMESTAMP)
private long getTime() {
	RevCommit c = parseCommit();
	if (c != null)
		return (long) c.getCommitTime() * 1000;
	return 0;
}
 
Example 11
Source File: CommitTimeRevFilter.java    From onedev with MIT License 5 votes vote down vote up
@Override
public boolean include(RevWalk walker, RevCommit cmit)
		throws StopWalkException, MissingObjectException,
		IncorrectObjectTypeException, IOException {
	// Since the walker sorts commits by commit time we can be
	// reasonably certain there is nothing remaining worth our
	// scanning if this commit is before the point in question.
	//
	if (cmit.getCommitTime() < when)
		throw StopWalkException.INSTANCE;
	return true;
}
 
Example 12
Source File: Link.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 5 votes vote down vote up
/**
 * It gets the commit closest to the Bug Open reposrt date
 * 
 * @param previous
 * @param git
 * @param fileName
 * @param linesMinus
 * @return
 */
private Suspect getSuspect(String previous, Git git, String fileName, List<Integer> linesMinus, PrintWriter l) {
   	RevCommit closestCommit = null; 
   	long tempDifference = Long.MAX_VALUE; 
   	for (int i : linesMinus){ 
   		try{ 
   			String sha = git.getBlameAt(previous,fileName,i);
   			if (sha == null)
   				break;
   			RevCommit commit = git.getCommit(sha,l); 
   			long difference =(issue.getOpen()/1000) - (commit.getCommitTime()); 
   			if (difference > 0){ 
   				if (difference < tempDifference ){
   					closestCommit = commit; 
   					tempDifference = difference; } 
   				}
   			} catch (Exception e){ 
   				e.printStackTrace();
   				l.println(e);
   			}
   	} 
   	if (closestCommit != null){ 
   		Long temp = Long.parseLong(closestCommit.getCommitTime()+"") * 1000; 
   		Suspect s = new Suspect(closestCommit.getName(), new Date(temp), fileName);
   	return s; 
   	}
 
	return null;
}
 
Example 13
Source File: GitMigrator.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
private void createSnapshots(Node saveSetNode, String relativeSnpFilePath){
    try {
        List<RevCommit> commits = findCommitsFor(relativeSnpFilePath);
        Map<String, RevTag> tags = loadTagsForRevisions(commits);
        for(RevCommit commit : commits){
            try (ObjectReader objectReader = git.getRepository().newObjectReader(); TreeWalk treeWalk = new TreeWalk(objectReader)) {
                CanonicalTreeParser treeParser = new CanonicalTreeParser();
                treeParser.reset(objectReader, commit.getTree());
                int treeIndex = treeWalk.addTree(treeParser);
                treeWalk.setFilter(PathFilter.create(relativeSnpFilePath));
                treeWalk.setRecursive(true);
                if (treeWalk.next()) {
                    AbstractTreeIterator iterator = treeWalk.getTree(treeIndex, AbstractTreeIterator.class);
                    ObjectId objectId = iterator.getEntryObjectId();
                    ObjectLoader objectLoader = objectReader.open(objectId);
                    RevTag tag = tags.get(commit.getName());
                    try (InputStream stream = objectLoader.openStream()) {
                        List<SnapshotItem> snapshotItems = FileReaderHelper.readSnapshot(stream);
                        if(tag != null){
                            System.out.println();
                        }
                        if(!isSnapshotCompatibleWithSaveSet(saveSetNode, snapshotItems)){
                            continue;
                        }
                        snapshotItems = setConfigPvIds(saveSetNode, snapshotItems);
                        Date commitTime = new Date(commit.getCommitTime() * 1000L);
                        Node snapshotNode = saveAndRestoreService.saveSnapshot(saveSetNode,
                                snapshotItems,
                                commitTime.toString(),
                                commit.getFullMessage());

                        snapshotNode = saveAndRestoreService.getNode(snapshotNode.getUniqueId());
                        Map<String, String> properties = snapshotNode.getProperties();
                        if(properties == null){
                            properties = new HashMap<>();
                        }
                        if(tag != null){
                            properties.put("golden", "true");
                            snapshotNode.setProperties(properties);
                        }
                        snapshotNode.setUserName(commit.getCommitterIdent().getName());
                        saveAndRestoreService.updateNode(snapshotNode);
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: Branch.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public int getTime() {
	RevCommit c = parseCommit();
	if (c != null)
		return c.getCommitTime();
	return 0;
}
 
Example 15
Source File: CommitTimeRevFilter.java    From onedev with MIT License 4 votes vote down vote up
@Override
public boolean include(RevWalk walker, RevCommit cmit)
		throws StopWalkException, MissingObjectException,
		IncorrectObjectTypeException, IOException {
	return cmit.getCommitTime() <= until && cmit.getCommitTime() >= when;
}
 
Example 16
Source File: GetDiffEntriesForCommitsAdapter.java    From coderadar with MIT License 4 votes vote down vote up
@Override
public List<DiffEntry> getDiffs(String projectRoot, String commitName1, String commitName2)
    throws UnableToGetDiffsFromCommitsException {
  try {
    Git git = Git.open(new File(projectRoot));
    Repository repository = git.getRepository();
    RevCommit commit1 = repository.parseCommit(ObjectId.fromString(commitName1));
    RevCommit commit2 = repository.parseCommit(ObjectId.fromString(commitName2));
    // change commits so that commit2 is the older one
    if (commit1.getCommitTime() > commit2.getCommitTime()) {
      RevCommit tmp = commit1;
      commit1 = commit2;
      commit2 = tmp;
    }

    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    ObjectId oldTree = commit1.getTree();
    oldTreeIter.reset(reader, oldTree);

    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    ObjectId newTree = commit2.getTree();
    newTreeIter.reset(reader, newTree);

    DiffFormatter df = new DiffFormatter(new ByteArrayOutputStream());
    df.setRepository(repository);
    List<DiffEntry> entries =
        df.scan(oldTreeIter, newTreeIter).stream()
            .map(
                diffEntry -> {
                  DiffEntry entry = new DiffEntry();
                  entry.setNewPath(diffEntry.getNewPath());
                  entry.setOldPath(diffEntry.getOldPath());
                  entry.setChangeType(
                      ChangeTypeMapper.jgitToCoderadar(diffEntry.getChangeType()).ordinal());
                  return entry;
                })
            .collect(Collectors.toList());
    git.close();
    return entries;
  } catch (IOException e) {
    throw new UnableToGetDiffsFromCommitsException(e.getMessage());
  }
}
 
Example 17
Source File: CommitTimeRevFilter.java    From onedev with MIT License 4 votes vote down vote up
@Override
public boolean include(RevWalk walker, RevCommit cmit)
		throws StopWalkException, MissingObjectException,
		IncorrectObjectTypeException, IOException {
	return cmit.getCommitTime() <= when;
}
 
Example 18
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;
}