Search in sources :

Example 41 with DiffEntry

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

the class TestCheckoutBuggyBuildSourceCode method testCheckoutPreviousBuildSourceCodeNoPR.

@Test
public void testCheckoutPreviousBuildSourceCodeNoPR() throws IOException, GitAPIException, RepairnatorConfigException {
    // INRIA/spoon
    int buildId = 221992429;
    int previousBuildId = 218213030;
    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(previousBuild, build, 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)

Example 42 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method applyChanges.

/**
 * <p>This method takes a range of commits (<code>c1..c2</code>) and performs manual update to ${karaf.home}.
 * If ${karaf.home} was also a checked out working copy, it'd be a matter of <code>git pull</code>. We may consider
 * this implementation, but now I don't want to keep <code>.git</code> directory in ${karaf.home}. Also, jgit
 * doesn't support <code>.git</code> <em>platform agnostic symbolic link</em>
 * (see: <code>git init --separate-git-dir</code>)</p>
 * <p>We don't have to fetch data from repository blobs, because <code>git</code> still points to checked-out
 * working copy</p>
 * <p>TODO: maybe we just have to copy <strong>all</strong> files from working copy to ${karaf.home}?</p>
 * @param git
 * @param commit1
 * @param commit2
 */
private void applyChanges(Git git, RevCommit commit1, RevCommit commit2) throws IOException, GitAPIException {
    File wcDir = git.getRepository().getWorkTree();
    List<DiffEntry> diff = this.gitPatchRepository.diff(git, commit1, commit2);
    // Changes to the lib dir get done in the lib.next directory.  Lets copy
    // the lib dir just in case we do have modification to it.
    File lib = new File(karafBase, "lib");
    if (lib.isDirectory()) {
        FileUtils.copyDirectory(lib, new File(karafBase, "lib.next"));
    }
    boolean libDirectoryChanged = false;
    for (DiffEntry de : diff) {
        DiffEntry.ChangeType ct = de.getChangeType();
        /*
             * old path:
             *  - file add: always /dev/null
             *  - file modify: always getNewPath()
             *  - file delete: always the file being deleted
             *  - file copy: source file the copy originates from
             *  - file rename: source file the rename originates from
             * new path:
             *  - file add: always the file being created
             *  - file modify: always getOldPath()
             *  - file delete: always /dev/null
             *  - file copy: destination file the copy ends up at
             *  - file rename: destination file the rename ends up at
             */
        String newPath = de.getNewPath();
        String oldPath = de.getOldPath();
        switch(ct) {
            case ADD:
            case MODIFY:
                Activator.log(LogService.LOG_DEBUG, "[PATCH-change] Modifying " + newPath);
                String targetPath = newPath;
                if (newPath.startsWith("lib/")) {
                    targetPath = "lib.next/" + newPath.substring(4);
                    libDirectoryChanged = true;
                }
                File srcFile = new File(wcDir, newPath);
                File destFile = new File(karafBase, targetPath);
                // we do exception for etc/overrides.properties
                if ("etc/overrides.properties".equals(newPath) && srcFile.exists() && srcFile.length() == 0) {
                    FileUtils.deleteQuietly(destFile);
                } else {
                    FileUtils.copyFile(srcFile, destFile);
                }
                break;
            case DELETE:
                Activator.log(LogService.LOG_DEBUG, "[PATCH-change] Deleting " + newPath);
                if (oldPath.startsWith("lib/")) {
                    oldPath = "lib.next/" + oldPath.substring(4);
                    libDirectoryChanged = true;
                }
                FileUtils.deleteQuietly(new File(karafBase, oldPath));
                break;
            case COPY:
            case RENAME:
                // not handled now
                break;
        }
    }
    if (!libDirectoryChanged) {
        // lib.next directory might not be needed.
        FileUtils.deleteDirectory(new File(karafBase, "lib.next"));
    }
}
Also used : ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 43 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project fabric8 by jboss-fuse.

the class GitConflictResolutionIT method reportingDiffs.

@Test
public void reportingDiffs() throws Exception {
    prepareChanges();
    ObjectReader reader = git.getRepository().newObjectReader();
    RevWalk rw = new RevWalk(git.getRepository());
    CanonicalTreeParser ctp1 = new CanonicalTreeParser();
    CanonicalTreeParser ctp2 = new CanonicalTreeParser();
    CanonicalTreeParser ctp3 = new CanonicalTreeParser();
    ctp1.reset(reader, rw.parseCommit(git.getRepository().resolve("master")).getTree());
    ctp2.reset(reader, rw.parseCommit(git.getRepository().resolve("custom")).getTree());
    ctp3.reset(reader, rw.parseCommit(git.getRepository().resolve("patched")).getTree());
    TreeWalk walk = new TreeWalk(reader);
    walk.addTree(ctp1);
    walk.addTree(ctp3);
    walk.setRecursive(true);
    List<DiffEntry> diffs = DiffEntry.scan(walk);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(baos);
    df.setDiffAlgorithm(DiffAlgorithm.getAlgorithm(DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setRepository(git.getRepository());
    df.format(diffs.get(0));
    // System.out.println(new String(baos.toByteArray()));
    AbbreviatedObjectId id1 = diffs.get(0).getOldId();
    AbbreviatedObjectId id2 = diffs.get(0).getNewId();
    byte[] bytes1 = reader.open(id1.toObjectId()).getBytes();
    byte[] bytes2 = reader.open(id2.toObjectId()).getBytes();
    RawText rt1 = new RawText(bytes1);
    RawText rt2 = new RawText(bytes2);
    EditList edits = DiffAlgorithm.getAlgorithm(DiffAlgorithm.SupportedAlgorithm.HISTOGRAM).diff(RawTextComparator.DEFAULT, rt1, rt2);
    int aCur = 0;
    for (Edit curEdit : edits) {
        boolean prolog = aCur < curEdit.getBeginA();
        if (prolog) {
            System.out.print("<div class=\"edit unchanged\">");
        }
        while (aCur < curEdit.getBeginA()) {
            System.out.println(rt1.getString(aCur++));
        }
        if (prolog) {
            System.out.print("</div>");
        }
        if (curEdit.getType() == Edit.Type.INSERT) {
            System.out.print("<div class=\"edit added\">");
            for (int i = curEdit.getBeginB(); i < curEdit.getEndB(); i++) {
                System.out.println(rt2.getString(i));
            }
            System.out.print("</div>");
        }
        if (curEdit.getType() == Edit.Type.REPLACE) {
            System.out.print("<div class=\"edit changed\"><div class=\"edit removed\">");
            for (int i = curEdit.getBeginA(); i < curEdit.getEndA(); i++) {
                System.out.println(rt1.getString(i));
            }
            System.out.print("</div><div class=\"edit added\">");
            for (int i = curEdit.getBeginB(); i < curEdit.getEndB(); i++) {
                System.out.println(rt2.getString(i));
            }
            aCur = curEdit.getEndA();
            System.out.print("</div></div>");
        }
    }
    boolean prolog = aCur < rt1.size();
    if (prolog) {
        System.out.print("<div class=\"edit unchanged\">");
    }
    while (aCur < rt1.size()) {
        System.out.println(rt1.getString(aCur++));
    }
    if (prolog) {
        System.out.print("</div>");
    }
}
Also used : Edit(org.eclipse.jgit.diff.Edit) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RawText(org.eclipse.jgit.diff.RawText) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) AbbreviatedObjectId(org.eclipse.jgit.lib.AbbreviatedObjectId) ObjectReader(org.eclipse.jgit.lib.ObjectReader) EditList(org.eclipse.jgit.diff.EditList) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) DiffEntry(org.eclipse.jgit.diff.DiffEntry) Test(org.junit.Test)

Example 44 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceIT method addPatch4.

/**
 * Patch 4 is rollup patch (doesn't contain descriptor, contains default.profile/io.fabric8.version.properties)
 * Adding it is not different that adding non-rollup patch. Installation is different
 * @throws IOException
 * @throws GitAPIException
 */
@Test
public void addPatch4() throws IOException, GitAPIException {
    initializationPerformedBaselineDistributionFoundInSystem();
    // prepare some ZIP patches
    preparePatchZip("src/test/resources/content/patch4", "target/karaf/patches/source/patch-4.zip", false);
    PatchManagement service = (PatchManagement) pm;
    PatchData patchData = service.fetchPatches(new File("target/karaf/patches/source/patch-4.zip").toURI().toURL()).get(0);
    assertThat(patchData.getId(), equalTo("patch-4"));
    Patch patch = service.trackPatch(patchData);
    GitPatchRepository repository = ((GitPatchManagementServiceImpl) pm).getGitPatchRepository();
    Git fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    // we should see remote branch for the patch, but without checking it out, it won't be available in the clone's local branches
    List<Ref> branches = fork.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
    Ref patchBranch = null;
    for (Ref remoteBranch : branches) {
        if (String.format("refs/remotes/origin/patch-%s", patchData.getId()).equals(remoteBranch.getName())) {
            patchBranch = remoteBranch;
            break;
        }
    }
    assertNotNull("Should find remote branch for the added patch", patchBranch);
    assertThat(patch.getManagedPatch().getCommitId(), equalTo(patchBranch.getObjectId().getName()));
    RevCommit patchCommit = new RevWalk(fork.getRepository()).parseCommit(patchBranch.getObjectId());
    // patch commit should be child of baseline commit
    RevCommit baselineCommit = new RevWalk(fork.getRepository()).parseCommit(patchCommit.getParent(0));
    // this baseline commit should be tagged "baseline-VERSION"
    Ref tag = fork.tagList().call().get(0);
    assertThat(tag.getName(), equalTo("refs/tags/baseline-6.2.0"));
    RevCommit baselineCommitFromTag = new RevWalk(fork.getRepository()).parseCommit(tag.getTarget().getObjectId());
    assertThat(baselineCommit.getId(), equalTo(baselineCommitFromTag.getId()));
    List<DiffEntry> patchDiff = repository.diff(fork, baselineCommit, patchCommit);
    int changes = SystemUtils.IS_OS_WINDOWS ? 8 : 9;
    assertThat("patch-4 should lead to " + changes + " changes", patchDiff.size(), equalTo(changes));
    for (Iterator<DiffEntry> iterator = patchDiff.iterator(); iterator.hasNext(); ) {
        DiffEntry de = iterator.next();
        if ("bin/start".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("bin/stop".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if (!SystemUtils.IS_OS_WINDOWS && "bin/setenv".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("etc/startup.properties".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("etc/my.properties".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.ADD) {
            iterator.remove();
        }
        if ("etc/system.properties".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("fabric/import/fabric/profiles/default.profile/io.fabric8.agent.properties".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("fabric/import/fabric/profiles/default.profile/io.fabric8.version.properties".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.MODIFY) {
            iterator.remove();
        }
        if ("patch-info.txt".equals(de.getNewPath()) && de.getChangeType() == DiffEntry.ChangeType.ADD) {
            iterator.remove();
        }
    }
    assertThat("Unknown changes in patch-4", patchDiff.size(), equalTo(0));
    // let's see the patch applied to baseline-6.2.0
    fork.checkout().setName("patch-4").setStartPoint("origin/patch-patch-4").setCreateBranch(true).call();
    String startupProperties = FileUtils.readFileToString(new File(fork.getRepository().getWorkTree(), "etc/startup.properties"));
    assertTrue(startupProperties.contains("org/ops4j/pax/url/pax-url-gopher/2.4.0/pax-url-gopher-2.4.0.jar=5"));
    repository.closeRepository(fork, true);
}
Also used : GitPatchRepository(io.fabric8.patch.management.impl.GitPatchRepository) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Ref(org.eclipse.jgit.lib.Ref) GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) Git(org.eclipse.jgit.api.Git) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry) Test(org.junit.Test)

Example 45 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project liferay-docs by liferay.

the class GitCompare method main.

public static void main(String[] args) throws GitAPIException, IOException {
    String docdir = args[0];
    String purposedir = args[1];
    String olderBranch = args[2];
    Repository repo = openGitRepository();
    String importBranch = repo.getBranch();
    AbstractTreeIterator oldTreeParser = gitTreeParser(repo, "refs/heads/" + olderBranch);
    AbstractTreeIterator importTreeParser = gitTreeParser(repo, "refs/heads/" + importBranch);
    List<DiffEntry> diff = new Git(repo).diff().setOldTree(oldTreeParser).setNewTree(importTreeParser).call();
    System.out.println("Creating ../git-modified-list.txt file");
    PrintWriter writer = new PrintWriter("git-modified-list.txt", "UTF-8");
    addTimeStamp("Comparing your " + importBranch + " branch to your older branch " + olderBranch + " .\nGenerated on", writer);
    System.out.println("Comparing your " + importBranch + " branch to your older branch " + olderBranch);
    boolean newDiff = false;
    String baseFilePath;
    if (System.getProperty("user.dir").contains(purposedir + "\\learning-paths") || System.getProperty("user.dir").contains(purposedir + "/learning-paths")) {
        baseFilePath = purposedir + "/learning-paths/" + docdir;
    } else {
        baseFilePath = purposedir + "/" + docdir + "/";
    }
    for (DiffEntry entry : diff) {
        String stringEntry = entry.toString();
        if (stringEntry.contains(baseFilePath)) {
            writer.println(stringEntry);
            System.out.println(stringEntry);
            newDiff = true;
        }
    }
    if (!newDiff) {
        System.out.println("There are no additions/modifications in ../" + baseFilePath);
        writer.println("There are no new additions/modifications to report");
    }
    writer.close();
    repo.close();
}
Also used : AbstractTreeIterator(org.eclipse.jgit.treewalk.AbstractTreeIterator) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry) PrintWriter(java.io.PrintWriter)

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