Search in sources :

Example 36 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project che by eclipse.

the class JGitDiffPage method writeNames.

private void writeNames(List<DiffEntry> diff, OutputStream out) throws IOException {
    PrintWriter writer = new PrintWriter(out);
    for (DiffEntry de : diff) {
        writer.print((de.getChangeType() == ChangeType.DELETE ? de.getOldPath() : de.getNewPath()) + (diff.size() != diff.indexOf(de) + 1 ? lineSeparator() : ""));
    }
    writer.flush();
}
Also used : PrintWriter(java.io.PrintWriter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 37 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project gerrit by GerritCodeReview.

the class PatchListLoader method readPatchList.

public PatchList readPatchList(Repository repo, RevWalk rw, ObjectInserter ins) throws IOException, PatchListNotAvailableException {
    ObjectReader reader = rw.getObjectReader();
    checkArgument(reader.getCreatedFromInserter() == ins);
    RawTextComparator cmp = comparatorFor(key.getWhitespace());
    try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
        RevCommit b = rw.parseCommit(key.getNewId());
        RevObject a = aFor(key, repo, rw, ins, b);
        if (a == null) {
            // TODO(sop) Remove this case.
            // This is an octopus merge commit which should be compared against the
            // auto-merge. However since we don't support computing the auto-merge
            // for octopus merge commits, we fall back to diffing against the first
            // parent, even though this wasn't what was requested.
            //
            ComparisonType comparisonType = ComparisonType.againstParent(1);
            PatchListEntry[] entries = new PatchListEntry[2];
            entries[0] = newCommitMessage(cmp, reader, null, b);
            entries[1] = newMergeList(cmp, reader, null, b, comparisonType);
            return new PatchList(a, b, true, comparisonType, entries);
        }
        ComparisonType comparisonType = getComparisonType(a, b);
        RevCommit aCommit = a instanceof RevCommit ? (RevCommit) a : null;
        RevTree aTree = rw.parseTree(a);
        RevTree bTree = b.getTree();
        df.setReader(reader, repo.getConfig());
        df.setDiffComparator(cmp);
        df.setDetectRenames(true);
        List<DiffEntry> diffEntries = df.scan(aTree, bTree);
        Set<String> paths = null;
        if (key.getOldId() != null && b.getParentCount() == 1) {
            PatchListKey newKey = PatchListKey.againstDefaultBase(key.getNewId(), key.getWhitespace());
            PatchListKey oldKey = PatchListKey.againstDefaultBase(key.getOldId(), key.getWhitespace());
            paths = Stream.concat(patchListCache.get(newKey, project).getPatches().stream(), patchListCache.get(oldKey, project).getPatches().stream()).map(PatchListEntry::getNewName).collect(toSet());
        }
        int cnt = diffEntries.size();
        List<PatchListEntry> entries = new ArrayList<>();
        entries.add(newCommitMessage(cmp, reader, comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b));
        boolean isMerge = b.getParentCount() > 1;
        if (isMerge) {
            entries.add(newMergeList(cmp, reader, comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b, comparisonType));
        }
        for (int i = 0; i < cnt; i++) {
            DiffEntry e = diffEntries.get(i);
            if (paths == null || paths.contains(e.getNewPath()) || paths.contains(e.getOldPath())) {
                FileHeader fh = toFileHeader(key, df, e);
                long oldSize = getFileSize(reader, e.getOldMode(), e.getOldPath(), aTree);
                long newSize = getFileSize(reader, e.getNewMode(), e.getNewPath(), bTree);
                entries.add(newEntry(aTree, fh, newSize, newSize - oldSize));
            }
        }
        return new PatchList(a, b, isMerge, comparisonType, entries.toArray(new PatchListEntry[entries.size()]));
    }
}
Also used : RevObject(org.eclipse.jgit.revwalk.RevObject) RawTextComparator(org.eclipse.jgit.diff.RawTextComparator) ArrayList(java.util.ArrayList) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) FileHeader(org.eclipse.jgit.patch.FileHeader) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 38 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project indy by Commonjava.

the class GitManager method verifyChangesExist.

private boolean verifyChangesExist(final Collection<String> paths) throws GitSubsystemException {
    return lockAnd(me -> {
        try {
            final DiffFormatter formatter = new DiffFormatter(System.out);
            formatter.setRepository(repo);
            final ObjectId oid = repo.resolve(Constants.HEAD);
            if (oid == null) {
                return true;
            }
            final RevWalk walk = new RevWalk(repo);
            final RevCommit commit = walk.parseCommit(oid);
            final RevTree treeWalk = walk.parseTree(commit);
            final List<TreeFilter> filters = new ArrayList<>();
            for (final String path : paths) {
                filters.add(PathFilter.create(path));
            }
            filters.add(TreeFilter.ANY_DIFF);
            walk.setTreeFilter(AndTreeFilter.create(filters));
            final CanonicalTreeParser tree = new CanonicalTreeParser();
            final ObjectReader oldReader = repo.newObjectReader();
            try {
                tree.reset(oldReader, treeWalk.getId());
            } finally {
                oldReader.release();
            }
            walk.dispose();
            final FileTreeIterator files = new FileTreeIterator(repo);
            final List<DiffEntry> entries = formatter.scan(tree, files);
            return entries != null && !entries.isEmpty();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to scan for actual changes among: %s. Reason: %s", e, paths, e.getMessage());
        }
    });
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) JoinString(org.commonjava.maven.atlas.ident.util.JoinString) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 39 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project searchcode-server by boyter.

the class IndexGitRepoJob method updateGitRepository.

/**
     * Update a git repository and return if it has changed and the differences
     */
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
    Repository localRepository = null;
    Git git = null;
    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));
        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);
        git.reset();
        git.clean();
        PullCommand pullCmd = git.pull();
        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }
        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");
        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;
            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
            ObjectReader reader = localRepository.newObjectReader();
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);
            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }
    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }
    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ArrayList(java.util.ArrayList) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) InvalidPathException(java.nio.file.InvalidPathException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 40 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project repairnator by Spirals-Team.

the class TestCheckoutBuggyBuildSourceCode method testCheckoutPreviousBuildSourceCodeNoPR2.

@Test
public void testCheckoutPreviousBuildSourceCodeNoPR2() throws IOException, GitAPIException, RepairnatorConfigException {
    // alibaba/fastjson
    int buildId = 222020421;
    int previousBuildId = 222016611;
    ScannedBuildStatus status = ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES;
    Build build = BuildHelper.getBuildFromId(buildId, null);
    assertThat(build, notNullValue());
    assertThat(buildId, is(build.getId()));
    assertThat(build.isPullRequest(), is(false));
    Build previousBuild = BuildHelper.getBuildFromId(previousBuildId, null);
    assertThat(previousBuild, notNullValue());
    assertThat(previousBuild.getId(), is(previousBuildId));
    assertThat(previousBuild.isPullRequest(), is(false));
    Path tmpDirPath = Files.createTempDirectory("test_checkoutprevious");
    File tmpDir = tmpDirPath.toFile();
    tmpDir.deleteOnExit();
    BuildToBeInspected toBeInspected = new BuildToBeInspected(build, previousBuild, status, "");
    ProjectInspector inspector = mock(ProjectInspector.class);
    when(inspector.getWorkspace()).thenReturn(tmpDir.getAbsolutePath());
    when(inspector.getRepoLocalPath()).thenReturn(tmpDir.getAbsolutePath() + "/repo");
    when(inspector.getRepoToPushLocalPath()).thenReturn(tmpDir.getAbsolutePath() + "/repotopush");
    when(inspector.getBuildToBeInspected()).thenReturn(toBeInspected);
    when(inspector.getPatchedBuild()).thenReturn(build);
    when(inspector.getBuggyBuild()).thenReturn(previousBuild);
    when(inspector.getGitHelper()).thenReturn(new GitHelper());
    JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath() + "/repo");
    when(inspector.getJobStatus()).thenReturn(jobStatus);
    CloneRepository cloneStep = new CloneRepository(inspector);
    CheckoutBuggyBuildSourceCode checkoutBuild = new CheckoutBuggyBuildSourceCode(inspector);
    cloneStep.setNextStep(checkoutBuild);
    cloneStep.execute();
    assertThat(checkoutBuild.getPipelineState(), is(PipelineState.PREVIOUSBUILDCODECHECKEDOUT));
    assertThat(jobStatus.getPipelineState(), is(PipelineState.PREVIOUSBUILDCODECHECKEDOUT));
    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));
}
Also used : Path(java.nio.file.Path) GitHelper(fr.inria.spirals.repairnator.process.git.GitHelper) ProjectInspector(fr.inria.spirals.repairnator.process.inspectors.ProjectInspector) BuildToBeInspected(fr.inria.spirals.repairnator.BuildToBeInspected) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) JobStatus(fr.inria.spirals.repairnator.process.inspectors.JobStatus) CloneRepository(fr.inria.spirals.repairnator.process.step.CloneRepository) Git(org.eclipse.jgit.api.Git) ScannedBuildStatus(fr.inria.spirals.repairnator.states.ScannedBuildStatus) Build(fr.inria.jtravis.entities.Build) ObjectReader(org.eclipse.jgit.lib.ObjectReader) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry) Test(org.junit.Test)

Aggregations

DiffEntry (org.eclipse.jgit.diff.DiffEntry)66 RevCommit (org.eclipse.jgit.revwalk.RevCommit)24 RevWalk (org.eclipse.jgit.revwalk.RevWalk)23 DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)22 ObjectReader (org.eclipse.jgit.lib.ObjectReader)21 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)20 IOException (java.io.IOException)19 Git (org.eclipse.jgit.api.Git)18 ObjectId (org.eclipse.jgit.lib.ObjectId)15 ArrayList (java.util.ArrayList)14 File (java.io.File)13 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)12 RevTree (org.eclipse.jgit.revwalk.RevTree)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 Path (java.nio.file.Path)8 Test (org.junit.Test)8 FileTreeIterator (org.eclipse.jgit.treewalk.FileTreeIterator)7 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)7 Ref (org.eclipse.jgit.lib.Ref)6 Repository (org.eclipse.jgit.lib.Repository)6