Java Code Examples for org.eclipse.jgit.treewalk.CanonicalTreeParser#reset()

The following examples show how to use org.eclipse.jgit.treewalk.CanonicalTreeParser#reset() . 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: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
private AbstractTreeIterator getTreeIterator( String commitId ) throws Exception {
  if ( commitId == null ) {
    return new EmptyTreeIterator();
  }
  if ( commitId.equals( WORKINGTREE ) ) {
    return new FileTreeIterator( git.getRepository() );
  } else if ( commitId.equals( INDEX ) ) {
    return new DirCacheIterator( git.getRepository().readDirCache() );
  } else {
    ObjectId id = git.getRepository().resolve( commitId );
    if ( id == null ) { // commitId does not exist
      return new EmptyTreeIterator();
    } else {
      CanonicalTreeParser treeIterator = new CanonicalTreeParser();
      try ( RevWalk rw = new RevWalk( git.getRepository() ) ) {
        RevTree tree = rw.parseTree( id );
        try ( ObjectReader reader = git.getRepository().newObjectReader() ) {
          treeIterator.reset( reader, tree.getId() );
        }
      }
      return treeIterator;
    }
  }
}
 
Example 2
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private void populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        pluginsToUpdate = new ArrayList<PluginToUpdate>();
        
        checkDiffEmpty(diffs);
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 3
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws IOException {
    if ("~~staged~~".equals(ref)) {
        return new DirCacheIterator(DirCache.read(repository));
    } else if ("~~unstaged~~".equals(ref)) {
        return new FileTreeIterator(repository);
    }

    try (RevWalk walk = new RevWalk(repository)) {
        ObjectId commitObjectId = repository.resolve(ref);
        if (commitObjectId == null) {
            throw new GitInvalidRefException(format("invalid git ref %s", ref));
        }

        log.debug("ref: {}, commit id: {}", ref, commitObjectId.toString());

        RevCommit commit = walk.parseCommit(commitObjectId);
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader objectReader = repository.newObjectReader()) {
            treeParser.reset(objectReader, tree.getId());
        }

        return treeParser;
    }
}
 
Example 4
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) {
	List<DiffEntry> diffs = new ArrayList<>();
	try (	DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);
			RevWalk revWalk = new RevWalk(repository);
			ObjectReader reader = repository.newObjectReader();) {
    	diffFormatter.setRepository(repository);
    	diffFormatter.setDetectRenames(true);
    	diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
    	
    	CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    	if (!oldRevId.equals(ObjectId.zeroId()))
    		oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree());
    	
    	CanonicalTreeParser newTreeParser = new CanonicalTreeParser();
    	if (!newRevId.equals(ObjectId.zeroId()))
    		newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree());
    	
    	for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) {
    		if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
    				|| !Objects.equal(entry.getOldMode(), entry.getNewMode())
    				|| entry.getOldId()==null || !entry.getOldId().isComplete()
    				|| entry.getNewId()== null || !entry.getNewId().isComplete()
    				|| !entry.getOldId().equals(entry.getNewId())) {
    			diffs.add(entry);
    		}
    	}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}			
	return diffs;
}
 
Example 5
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws GitAPIException
 * @throws IOException
 */
List<DiffEntry> getChanges() throws GitAPIException, IOException {
  // get tree for last processed commit
  ObjectId oldHeadTree = git.getRepository().resolve(this.lastProcessedGitHash + "^{tree}");

  // refresh to latest and reset hard to handle forced pushes
  this.git.fetch()
      .setRemote(REMOTE_NAME)
      .setCredentialsProvider(getCredentialsProvider())
      .setTransportConfigCallback(buildTransportConfigCallback())
      .call();
  // reset hard to get a clean working set since pull --rebase may leave files around
  this.git.reset().setMode(ResetCommand.ResetType.HARD).setRef(REMOTE_NAME + "/" + this.branchName).call();

  ObjectId head = this.git.getRepository().resolve("HEAD");
  ObjectId headTree = this.git.getRepository().resolve("HEAD^{tree}");

  // remember the hash for the current HEAD. This will be checkpointed after the diff is processed.
  latestGitHash = head.getName();

  // diff old and new heads to find changes
  ObjectReader reader = this.git.getRepository().newObjectReader();
  CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
  oldTreeIter.reset(reader, oldHeadTree);
  CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
  newTreeIter.reset(reader, headTree);

  return this.git.diff()
      .setNewTree(newTreeIter)
      .setOldTree(oldTreeIter)
      .setShowNameAndStatusOnly(true)
      .call();
}
 
Example 6
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private boolean populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        if (diffs.isEmpty()) {
            System.out.println("No diff");
            return false;
        }else{
            return true;
        }
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }return true;//assume true
}
 
Example 7
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParserHelper(RevWalk walk, RevCommit commit)
    throws IOException, MissingObjectException, IncorrectObjectTypeException {
  RevTree tree = walk.parseTree(commit.getTree().getId());
  CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
  try (ObjectReader oldReader = repo.newObjectReader()) {
    oldTreeParser.reset(oldReader, tree.getId());
  }
  return oldTreeParser;
}
 
Example 8
Source File: PGA.java    From coming with MIT License 5 votes vote down vote up
private AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(repository.resolve(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser treeParser = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    treeParser.reset(reader, tree.getId());

    walk.dispose();

    return treeParser;
}
 
Example 9
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 5 votes vote down vote up
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException,
        MissingObjectException,
        IncorrectObjectTypeException {
    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();
    oldTreeParser.reset(oldReader, tree.getId());
    walk.dispose();
    return oldTreeParser;
}
 
Example 10
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException {
	final ObjectId id = db.resolve(name);
	if (id == null)
		throw new IllegalArgumentException(name);
	final CanonicalTreeParser p = new CanonicalTreeParser();
	final ObjectReader or = db.newObjectReader();
	try {
		p.reset(or, new RevWalk(db).parseTree(id));
		return p;
	} finally {
		or.close();
	}
}
 
Example 11
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Returns the Canonical Tree Parser representation of a commit.
 *
 * @param commit Commit in the repository.
 * @return CanonicalTreeParser representing the tree for the commit.
 * @throws IOException
 */
private CanonicalTreeParser getTree(String commit) throws IOException
{
    CanonicalTreeParser tree = new CanonicalTreeParser();
    ObjectReader reader = repository.newObjectReader();
    ObjectId head = repository.resolve(commit + "^{tree}");
    tree.reset(reader, head);
    return tree;
}
 
Example 12
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AbstractTreeIterator getIterator (String commit, ObjectReader or) throws IOException, GitException {
    Repository repository = getRepository();
    switch (commit) {
        case Constants.HEAD:
            return getHeadIterator(or);
        case GitClient.INDEX:
            return new DirCacheIterator(repository.readDirCache());
        case GitClient.WORKING_TREE:
            return new FileTreeIterator(repository);
        default:
            CanonicalTreeParser p = new CanonicalTreeParser();
            p.reset(or, Utils.findCommit(repository, commit).getTree());
            return p;
    }
}
 
Example 13
Source File: TestCheckoutBuggyBuildSourceCode.java    From repairnator with MIT License 4 votes vote down vote up
@Test
public void testCheckoutPreviousBuildSourceCodeNoPR() throws IOException, GitAPIException {
    long buildId = 221992429; // INRIA/spoon
    long previousBuildId = 218213030;
    ScannedBuildStatus status = ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES;

    Build build = this.checkBuildAndReturn(buildId, false);
    Build previousBuild = this.checkBuildAndReturn(previousBuildId, false);

    tmpDir = Files.createTempDirectory("test_checkoutprevious").toFile();

    BuildToBeInspected toBeInspected = new BuildToBeInspected(previousBuild, build, status, "");

    JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath()+"/repo");

    ProjectInspector inspector = ProjectInspectorMocker.mockProjectInspector(jobStatus, tmpDir, toBeInspected);

    CloneRepository cloneStep = new CloneRepository(inspector);
    CheckoutBuggyBuildSourceCode checkoutBuild = new CheckoutBuggyBuildSourceCode(inspector, true);

    cloneStep.addNextStep(checkoutBuild);
    cloneStep.execute();

    List<StepStatus> stepStatusList = jobStatus.getStepStatuses();
    assertThat(stepStatusList.size(), is(2));
    StepStatus checkoutStatus = stepStatusList.get(1);
    assertThat(checkoutStatus.getStep(), is(checkoutBuild));

    for (StepStatus stepStatus : stepStatusList) {
        assertThat(stepStatus.isSuccess(), is(true));
    }

    assertThat(checkoutBuild.isShouldStop(), is(false));

    Git gitDir = Git.open(new File(tmpDir, "repo"));

    Iterable<RevCommit> logs = gitDir.log().call();

    Iterator<RevCommit> iterator = logs.iterator();
    boolean foundRightCommitAfterRepairCommits = false;
    boolean foundUndoSourceCodeCommit = false;
    boolean stopSearch = false;

    while (iterator.hasNext() && !stopSearch) {
        RevCommit revCommit = iterator.next();

        if (revCommit.getShortMessage().equals("Undo changes on source code")) {
            foundUndoSourceCodeCommit = true;
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            ObjectReader reader = gitDir.getRepository().newObjectReader();
            RevCommit prevCommit = iterator.next();
            oldTreeIter.reset(reader, prevCommit.getTree());
            newTreeIter.reset(reader, revCommit.getTree());

            List<DiffEntry> diff = gitDir.diff().setOldTree(oldTreeIter).setNewTree(newTreeIter).call();

            for (DiffEntry entry : diff) {
                assertThat(entry.getOldPath(), startsWith("src/main/java/"));
            }

            revCommit = prevCommit;
        }

        if (revCommit.getName().equals(build.getCommit().getSha())) {
            foundRightCommitAfterRepairCommits = true;
        }

        if (!revCommit.getShortMessage().contains("repairnator")) {
            stopSearch = true;
        }

        if (foundRightCommitAfterRepairCommits && foundUndoSourceCodeCommit) {
            stopSearch = true;
        }
    }

    assertThat(foundRightCommitAfterRepairCommits, is(true));
    assertThat(foundUndoSourceCodeCommit, is(true));
}
 
Example 14
Source File: TestCheckoutBuggyBuildSourceCode.java    From repairnator with MIT License 4 votes vote down vote up
@Test
public void testCheckoutPreviousBuildSourceCodeNoPR2() throws IOException, GitAPIException {
    long buildId = 222020421; // alibaba/fastjson
    long previousBuildId = 222016611;
    ScannedBuildStatus status = ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES;

    Build build = this.checkBuildAndReturn(buildId, false);
    Build previousBuild = this.checkBuildAndReturn(previousBuildId, false);

    tmpDir = Files.createTempDirectory("test_checkoutprevious").toFile();

    BuildToBeInspected toBeInspected = new BuildToBeInspected(previousBuild, build, status, "");

    JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath()+"/repo");

    ProjectInspector inspector = ProjectInspectorMocker.mockProjectInspector(jobStatus, tmpDir, toBeInspected);

    CloneRepository cloneStep = new CloneRepository(inspector);
    CheckoutBuggyBuildSourceCode checkoutBuild = new CheckoutBuggyBuildSourceCode(inspector, true);

    cloneStep.addNextStep(checkoutBuild);
    cloneStep.execute();

    List<StepStatus> stepStatusList = jobStatus.getStepStatuses();
    assertThat(stepStatusList.size(), is(2));
    StepStatus checkoutStatus = stepStatusList.get(1);
    assertThat(checkoutStatus.getStep(), is(checkoutBuild));

    for (StepStatus stepStatus : stepStatusList) {
        assertThat(stepStatus.isSuccess(), is(true));
    }

    assertThat(checkoutBuild.isShouldStop(), is(false));

    Git gitDir = Git.open(new File(tmpDir, "repo"));

    Iterable<RevCommit> logs = gitDir.log().call();

    Iterator<RevCommit> iterator = logs.iterator();
    boolean foundRightCommitAfterRepairCommits = false;
    boolean foundUndoSourceCodeCommit = false;
    boolean stopSearch = false;

    while (iterator.hasNext() && !stopSearch) {
        RevCommit revCommit = iterator.next();

        if (revCommit.getShortMessage().equals("Undo changes on source code")) {
            foundUndoSourceCodeCommit = true;
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            ObjectReader reader = gitDir.getRepository().newObjectReader();
            RevCommit prevCommit = iterator.next();
            oldTreeIter.reset(reader, prevCommit.getTree());
            newTreeIter.reset(reader, revCommit.getTree());

            List<DiffEntry> diff = gitDir.diff().setOldTree(oldTreeIter).setNewTree(newTreeIter).call();

            for (DiffEntry entry : diff) {
                assertThat(entry.getOldPath(), startsWith("src/main/java/"));
            }

            revCommit = prevCommit;
        }

        if (revCommit.getName().equals(build.getCommit().getSha())) {
            foundRightCommitAfterRepairCommits = true;
        }

        if (!revCommit.getShortMessage().contains("repairnator")) {
            stopSearch = true;
        }

        if (foundRightCommitAfterRepairCommits && foundUndoSourceCodeCommit) {
            stopSearch = true;
        }
    }

    assertThat(foundRightCommitAfterRepairCommits, is(true));
    assertThat(foundUndoSourceCodeCommit, is(true));
}
 
Example 15
Source File: TestCheckoutBuggyBuildSourceCode.java    From repairnator with MIT License 4 votes vote down vote up
@Test
public void testCheckoutPreviousBuildSourceCodeWithPR() throws IOException, GitAPIException {
    long buildId = 223248816; // HubSpot/Singularity
    long previousBuildId = 222209171;
    ScannedBuildStatus status = ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES;

    Build build = this.checkBuildAndReturn(buildId, true);
    Build previousBuild = this.checkBuildAndReturn(previousBuildId, true);

    tmpDir = Files.createTempDirectory("test_checkoutprevious").toFile();

    BuildToBeInspected toBeInspected = new BuildToBeInspected(previousBuild, build, status, "");

    JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath()+"/repo");

    ProjectInspector inspector = ProjectInspectorMocker.mockProjectInspector(jobStatus, tmpDir, toBeInspected);

    CloneRepository cloneStep = new CloneRepository(inspector);
    CheckoutBuggyBuildSourceCode checkoutBuild = new CheckoutBuggyBuildSourceCode(inspector, true);

    cloneStep.addNextStep(checkoutBuild);
    cloneStep.execute();

    List<StepStatus> stepStatusList = jobStatus.getStepStatuses();
    assertThat(stepStatusList.size(), is(2));
    StepStatus checkoutStatus = stepStatusList.get(1);
    assertThat(checkoutStatus.getStep(), is(checkoutBuild));

    for (StepStatus stepStatus : stepStatusList) {
        assertThat(stepStatus.isSuccess(), is(true));
    }

    assertThat(checkoutBuild.isShouldStop(), is(false));

    Git gitDir = Git.open(new File(tmpDir, "repo"));

    Iterable<RevCommit> logs = gitDir.log().call();

    Iterator<RevCommit> iterator = logs.iterator();
    boolean foundRightCommitAfterRepairCommits = false;
    boolean foundUndoSourceCodeCommit = false;
    boolean stopSearch = false;

    while (iterator.hasNext() && !stopSearch) {
        RevCommit revCommit = iterator.next();

        System.out.println(revCommit.getShortMessage());
        if (revCommit.getShortMessage().equals("Undo changes on source code")) {
            foundUndoSourceCodeCommit = true;
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            ObjectReader reader = gitDir.getRepository().newObjectReader();
            RevCommit prevCommit = iterator.next();
            oldTreeIter.reset(reader, prevCommit.getTree());
            newTreeIter.reset(reader, revCommit.getTree());

            List<DiffEntry> diff = gitDir.diff().setOldTree(oldTreeIter).setNewTree(newTreeIter).call();

            for (DiffEntry entry : diff) {
                assertThat(entry.getOldPath(), startsWith("src/main/java/"));
            }

            revCommit = prevCommit;
        }

        if (!revCommit.getShortMessage().contains("repairnator") && !revCommit.getShortMessage().contains("merge")) {
            stopSearch = true;
        }
    }

    assertThat(foundUndoSourceCodeCommit, is(true));
}
 
Example 16
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public DiffConflictedFile getDiffForConflictedFile(String siteId, String path)
        throws ServiceLayerException, CryptoException {
    DiffConflictedFile diffResult = new DiffConflictedFile();
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    try (Git git = new Git(repo)) {
        List<ObjectId> mergeHeads = repo.readMergeHeads();
        ObjectId mergeCommitId = mergeHeads.get(0);
        logger.debug("Get content for studio version of conflicted file " + path + " for site " + siteId);
        InputStream studioVersionIs = contentRepository.getContentVersion(siteId, path, Constants.HEAD);
        diffResult.setStudioVersion(IOUtils.toString(studioVersionIs));
        logger.debug("Get content for remote version of conflicted file " + path + " for site " + siteId);
        InputStream remoteVersionIs = contentRepository.getContentVersion(siteId, path, mergeCommitId.getName());
        diffResult.setRemoteVersion(IOUtils.toString(remoteVersionIs));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        logger.debug("Get diff between studio and remote version of conflicted file " + path + " for site "
                + siteId);
        RevTree headTree = helper.getTreeForCommit(repo, Constants.HEAD);
        RevTree remoteTree = helper.getTreeForCommit(repo, mergeCommitId.getName());

        try (ObjectReader reader = repo.newObjectReader()) {
            CanonicalTreeParser headCommitTreeParser = new CanonicalTreeParser();
            CanonicalTreeParser remoteCommitTreeParser = new CanonicalTreeParser();
            headCommitTreeParser.reset(reader, headTree.getId());
            remoteCommitTreeParser.reset(reader, remoteTree.getId());

            // Diff the two commit Ids
            git.diff()
                    .setPathFilter(PathFilter.create(helper.getGitPath(path)))
                    .setOldTree(headCommitTreeParser)
                    .setNewTree(remoteCommitTreeParser)
                    .setOutputStream(baos)
                    .call();
            diffResult.setDiff(baos.toString());
        }


    } catch (IOException | GitAPIException e) {
        logger.error("Error while getting diff for conflicting file " + path + " site " + siteId);
        throw new ServiceLayerException("Error while getting diff for conflicting file " + path + " site " + siteId);
    }
    return diffResult;
}
 
Example 17
Source File: GitHelper.java    From repairnator with MIT License 4 votes vote down vote up
public void computePatchStats(JobStatus jobStatus, Git git, RevCommit headRev, RevCommit commit) {
    try {
        ObjectReader reader = git.getRepository().newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, headRev.getTree());
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, commit.getTree());

        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(git.getRepository());
        diffFormatter.setContext(0);
        List<DiffEntry> entries = diffFormatter.scan(newTreeIter, oldTreeIter);

        int nbLineAdded = 0;
        int nbLineDeleted = 0;
        Set<String> changedFiles = new HashSet<>();
        Set<String> addedFiles = new HashSet<>();
        Set<String> deletedFiles = new HashSet<>();

        for (DiffEntry entry : entries) {
            String path;
            if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                path = entry.getOldPath();
            } else {
                path = entry.getNewPath();
            }
            if (!jobStatus.isCreatedFileToPush(path) && path.endsWith(".java")) {
                if (entry.getChangeType() == DiffEntry.ChangeType.MODIFY ||
                        entry.getChangeType() == DiffEntry.ChangeType.RENAME) {
                    changedFiles.add(path);
                } else if (entry.getChangeType() == DiffEntry.ChangeType.ADD ||
                        entry.getChangeType() == DiffEntry.ChangeType.COPY) {
                    addedFiles.add(path);
                } else if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) {
                    deletedFiles.add(path);
                }

                FileHeader fileHeader = diffFormatter.toFileHeader(entry);
                List<? extends HunkHeader> hunks = fileHeader.getHunks();
                for (HunkHeader hunk : hunks) {
                    EditList edits = hunk.toEditList();
                    for (Edit edit : edits) {
                        switch (edit.getType()) {
                            case INSERT:
                                nbLineAdded += edit.getLengthB();
                                break;

                            case DELETE:
                                nbLineDeleted += edit.getLengthA();
                                break;

                            case REPLACE:
                                int diff = edit.getLengthA() - edit.getLengthB();
                                if (diff > 0) {
                                    nbLineAdded += edit.getLengthA();
                                    nbLineDeleted += edit.getLengthB();
                                } else {
                                    nbLineDeleted += edit.getLengthA();
                                    nbLineAdded += edit.getLengthB();
                                }
                                break;

                            case EMPTY:
                                break;
                        }
                    }
                }
            }
        }

        PatchDiff patchDiff = jobStatus.getProperties().getPatchDiff();
        patchDiff.getFiles().setNumberAdded(addedFiles.size());
        patchDiff.getFiles().setNumberChanged(changedFiles.size());
        patchDiff.getFiles().setNumberDeleted(deletedFiles.size());
        patchDiff.getLines().setNumberAdded(nbLineAdded);
        patchDiff.getLines().setNumberDeleted(nbLineDeleted);
    } catch (IOException e) {
        this.getLogger().error("Error while computing stat on the patch.", e);
    }
}
 
Example 18
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 19
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 20
Source File: GitServiceImpl.java    From apidiff with MIT License 4 votes vote down vote up
@Override
public Map<ChangeType, List<GitFile>> fileTreeDiff(Repository repository, RevCommit commitNew) throws Exception {
       
	Map<ChangeType, List<GitFile>> mapDiff = new HashMap<ChangeType, List<GitFile>>();
	mapDiff.put(ChangeType.ADD, new ArrayList<>());
	mapDiff.put(ChangeType.COPY, new ArrayList<>());
	mapDiff.put(ChangeType.DELETE, new ArrayList<>());
	mapDiff.put(ChangeType.MODIFY, new ArrayList<>());
	mapDiff.put(ChangeType.RENAME, new ArrayList<>());
	
	if(commitNew.getParentCount() == 0){
		this.logger.warn("Commit don't have parent [commitId="+commitNew.getId().getName()+"]");
		return mapDiff;
	}
      
	ObjectId headOld = commitNew.getParent(0).getTree(); //Commit pai no grafo.
	ObjectId headNew = commitNew.getTree(); //Commit corrente.

       // prepare the two iterators to compute the diff between
	ObjectReader reader = repository.newObjectReader();
	
	CanonicalTreeParser treeRepositoryOld = new CanonicalTreeParser();
	treeRepositoryOld.reset(reader, headOld);
	
	CanonicalTreeParser treeRepositoryNew = new CanonicalTreeParser();
	treeRepositoryNew.reset(reader, headNew);
	
	// finally get the list of changed files
	List<DiffEntry> diffs = new Git(repository).diff()
	                    .setNewTree(treeRepositoryNew)
	                    .setOldTree(treeRepositoryOld)
	                    .setShowNameAndStatusOnly(true)
	                    .call();
	
       for (DiffEntry entry : diffs) {
       	if(UtilTools.isJavaFile(entry.getOldPath()) || UtilTools.isJavaFile(entry.getNewPath())) {
       		String pathNew =  "/dev/null".equals(entry.getNewPath())?null:entry.getNewPath();
       		String pathOld =  "/dev/null".equals(entry.getOldPath())?null:entry.getOldPath();
       		GitFile file = new GitFile(pathOld, pathNew, entry.getChangeType());
       		mapDiff.get(entry.getChangeType()).add(file);
       	}
       }
       return mapDiff;
}