Search in sources :

Example 51 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project maven-scm by apache.

the class JGitUtils method getFilesInCommit.

/**
 * get a list of all files in the given commit
 *
 * @param repository the repo
 * @param commit     the commit to get the files from
 * @return a list of files included in the commit
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws CorruptObjectException
 * @throws IOException
 */
public static List<ScmFile> getFilesInCommit(Repository repository, RevCommit commit) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    List<ScmFile> list = new ArrayList<ScmFile>();
    if (JGitUtils.hasCommits(repository)) {
        RevWalk rw = new RevWalk(repository);
        RevCommit realParant = commit.getParentCount() > 0 ? commit.getParent(0) : commit;
        RevCommit parent = rw.parseCommit(realParant.getId());
        DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
        df.setRepository(repository);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);
        List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
        for (DiffEntry diff : diffs) {
            list.add(new ScmFile(diff.getNewPath(), ScmFileStatus.CHECKED_IN));
        }
        rw.release();
    }
    return list;
}
Also used : ArrayList(java.util.ArrayList) RevWalk(org.eclipse.jgit.revwalk.RevWalk) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ScmFile(org.apache.maven.scm.ScmFile) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 52 with DiffEntry

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

the class GitPatchManagementServiceIT method addPatch4.

/**
 * Patch 4 is rollup patch (doesn't contain descriptor, contains etc/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-7.0.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 ? 7 : 8;
    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 ("etc/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-7.0.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"), "UTF-8");
    assertTrue(startupProperties.contains("mvn\\:org.ops4j.pax.url/pax-url-gopher/2.4.0=5"));
    repository.closeRepository(fork, true);
}
Also used : GitPatchRepository(org.jboss.fuse.patch.management.impl.GitPatchRepository) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Ref(org.eclipse.jgit.lib.Ref) GitPatchManagementServiceImpl(org.jboss.fuse.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 53 with DiffEntry

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

the class DiffUtils method generateDiffReport.

/**
 * <p>Having four commits, generate single, HTML report about all modified files</p>
 * <p>Please excuse inline html code.</p>
 * @param patch
 * @param git
 * @param conflicts
 * @param base
 * @param ours
 * @param theirs
 * @param resolved
 * @param result
 */
public static void generateDiffReport(Patch patch, PatchResult patchResult, Git git, Set<String> conflicts, RevCommit base, RevCommit ours, RevCommit theirs, RevCommit resolved, Writer result) throws IOException {
    ObjectReader reader = git.getRepository().newObjectReader();
    CanonicalTreeParser ctpBase = new CanonicalTreeParser();
    CanonicalTreeParser ctpOurs = new CanonicalTreeParser();
    CanonicalTreeParser ctpTheirs = new CanonicalTreeParser();
    CanonicalTreeParser ctpResolved = new CanonicalTreeParser();
    ctpBase.reset(reader, base.getTree());
    ctpOurs.reset(reader, ours.getTree());
    ctpTheirs.reset(reader, theirs.getTree());
    ctpResolved.reset(reader, resolved.getTree());
    // this map will contain 3 diffs for each file/path:
    // 0 - diff between base and "ours" ("ours" depends on patch kind and it's really "ours" in P-Patch,
    // because patch change is cherry-picked on top of custom change. In R-Patch, custom changes come after
    // patch, so they're called "theirs" in diff/git terminology)
    // 1 - diff between base and "theirs" (see above)
    // 2 - diff between base and resolved, effective and final state of history
    Map<String, DiffEntry[]> report = new LinkedHashMap<>();
    // 1. base -> ours
    TreeWalk walk = new TreeWalk(reader);
    walk.addTree(ctpBase);
    walk.addTree(ctpOurs);
    walk.setRecursive(true);
    List<DiffEntry> diffs = DiffEntry.scan(walk);
    diffs.forEach(de -> collect(report, de, 0));
    // 2. base -> theirs
    walk.reset();
    ctpBase.reset(reader, base.getTree());
    walk.addTree(ctpBase);
    walk.addTree(ctpTheirs);
    walk.setRecursive(true);
    diffs = DiffEntry.scan(walk);
    diffs.forEach(de -> collect(report, de, 1));
    // 3. base -> resolved
    walk.reset();
    ctpBase.reset(reader, base.getTree());
    walk.addTree(ctpBase);
    walk.addTree(ctpResolved);
    walk.setRecursive(true);
    diffs = DiffEntry.scan(walk);
    diffs.forEach(de -> collect(report, de, 2));
    // report generation
    PatchData pd = patchResult.getPatchData();
    result.write(reportHeader.replace("@PATCH_ID@", pd.getId()));
    PatchReport pr = patchResult.getReport();
    result.write("<table class=\"summary\">\n" + "        <tr>\n" + "            <td class=\"f\">Patch ID:</td><td>" + pr.getId() + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">Patch type:</td><td>" + (pr.isRollup() ? "rollup" : "non-rollup") + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">Installation date:</td><td>" + DATE.format(pr.getTimestamp()) + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">Bundles updated</td><td>" + pr.getUpdatedBundles() + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">Features updated</td><td>" + pr.getUpdatedFeatures() + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">Features overriden</td><td>" + pr.getOverridenFeatures() + "</td>\n" + "        </tr>\n" + "        <tr>\n" + "            <td class=\"f\">File conflicts</td><td>" + conflicts.size() + "</td>\n" + "        </tr>\n" + "    </table>\n" + "</div>\n");
    if (conflicts.size() > 0) {
        result.write("<h1 class=\"header\">\n" + "  <div>Conflicting files</div>\n" + "</h1>\n");
    }
    for (Map.Entry<String, DiffEntry[]> e : report.entrySet()) {
        if (!conflicts.contains(e.getKey())) {
            // we don't care about diffs that aren't really conflicts
            continue;
        }
        result.write(fileHeader1);
        result.write(e.getKey());
        result.write(fileHeader2);
        // we have max 3 entries (not all entries may be present
        result.write("<td class=\"side\">\n" + "          <div class=\"header\">Custom version</div>\n" + "          <div class=\"content" + (e.getValue()[0] != null ? "" : " empty") + "\">");
        if (e.getValue()[0] != null) {
            // custom change
            diff(git, reader, e.getValue()[0], result);
        } else {
            result.write("No change");
        }
        result.write("</div>\n" + "        </td>");
        result.write("<td class=\"side\">\n" + "          <div class=\"header\">Patch</div>\n" + "          <div class=\"content" + (e.getValue()[1] != null ? "" : " empty") + "\">");
        if (e.getValue()[1] != null) {
            // patch change
            diff(git, reader, e.getValue()[1], result);
        } else {
            result.write("No change");
        }
        result.write("</div>\n" + "        </td>");
        result.write("<td class=\"side\">\n" + "          <div class=\"header\">Final version</div>\n" + "          <div class=\"content" + (e.getValue()[2] != null ? "" : " empty") + "\">");
        if (e.getValue()[2] != null) {
            // effective change - should always be available
            // or maybe not when both patch and user removed the file?
            diff(git, reader, e.getValue()[2], result);
        } else {
            result.write("No change");
        }
        result.write("</div>\n" + "        </td>");
        result.write(fileFooter);
    }
    result.write(reportFooter);
}
Also used : PatchData(org.jboss.fuse.patch.management.PatchData) PatchReport(org.jboss.fuse.patch.management.PatchReport) ObjectReader(org.eclipse.jgit.lib.ObjectReader) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) LinkedHashMap(java.util.LinkedHashMap) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 54 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project ontrack by nemerosa.

the class GitRepositoryClientImpl method unifiedDiff.

@Override
public String unifiedDiff(String from, String to, Predicate<String> pathFilter) {
    try {
        GitRange range = range(from, to);
        // Diff command
        List<DiffEntry> entries = git.diff().setShowNameAndStatusOnly(true).setOldTree(getTreeIterator(range.getFrom().getId())).setNewTree(getTreeIterator(range.getTo().getId())).call();
        // Filtering the entries
        entries = entries.stream().filter(entry -> pathFilter.test(entry.getOldPath()) || pathFilter.test(entry.getNewPath())).collect(Collectors.toList());
        // Output
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        // Formatting
        DiffFormatter formatter = new DiffFormatter(output);
        formatter.setRepository(git.getRepository());
        entries.forEach(entry -> formatDiffEntry(formatter, entry));
        // OK
        return Utils.toString(output.toByteArray());
    } catch (GitAPIException e) {
        throw new GitRepositoryAPIException(repository.getRemote(), e);
    } catch (IOException e) {
        throw new GitRepositoryIOException(repository.getRemote(), e);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 55 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project zeppelin by apache.

the class GitNotebookRepo method checkpoint.

/* implemented as git add+commit
   * @param noteId is the noteId
   * @param noteName name of the note
   * @param commitMessage is a commit message (checkpoint message)
   * (non-Javadoc)
   * @see org.apache.zeppelin.notebook.repo.VFSNotebookRepo#checkpoint(String, String)
   */
@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;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) DirCache(org.eclipse.jgit.dircache.DirCache) DiffEntry(org.eclipse.jgit.diff.DiffEntry) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

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