Example usage for org.eclipse.jgit.diff DiffEntry getOldId

List of usage examples for org.eclipse.jgit.diff DiffEntry getOldId

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff DiffEntry getOldId.

Prototype

public AbbreviatedObjectId getOldId() 

Source Link

Document

Get the old object id from the index.

Usage

From source file:ShowFileDiff.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    Repository repository = null; //CookbookHelper.openJGitCookbookRepository();

    // the diff works on TreeIterators, we prepare two for the two branches
    AbstractTreeIterator oldTreeParser = prepareTreeParser(repository,
            "09c65401f3730eb3e619c33bf31e2376fb393727");
    AbstractTreeIterator newTreeParser = prepareTreeParser(repository,
            "aa31703b65774e4a06010824601e56375a70078c");

    // then the procelain diff-command returns a list of diff entries
    List<DiffEntry> diff = new Git(repository).diff().setOldTree(oldTreeParser).setNewTree(newTreeParser)
            .setPathFilter(PathFilter.create("README.md")).call();
    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
        DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setRepository(repository);
        formatter.format(entry);/*w  w w .j  av a2 s . c  o m*/
    }

    repository.close();
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private static void writeGitLinkDiffText(OutputStream o, DiffEntry ent) throws IOException {
    if (ent.getOldMode() == GITLINK) {
        o.write(encodeASCII("-Subproject commit " + ent.getOldId().name() //$NON-NLS-1$
                + "\n")); //$NON-NLS-1$
    }/*from   w ww .ja va2  s .  c om*/
    if (ent.getNewMode() == GITLINK) {
        o.write(encodeASCII("+Subproject commit " + ent.getNewId().name() //$NON-NLS-1$
                + "\n")); //$NON-NLS-1$
    }
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

public FormatResult getFormatResult(DiffEntry ent) throws IOException {
    final FormatResult res = new FormatResult();
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final EditList editList;
    final FileHeader.PatchType type;

    formatHeader(buf, ent);/*from   w w w . ja  va  2  s .  c o  m*/

    if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) {
        formatOldNewPaths(buf, ent);
        writeGitLinkDiffText(buf, ent);
        editList = new EditList();
        type = PatchType.UNIFIED;

    } else if (ent.getOldId() == null || ent.getNewId() == null) {
        // Content not changed (e.g. only mode, pure rename)
        editList = new EditList();
        type = PatchType.UNIFIED;

    } else {
        assertHaveRepository();

        byte[] aRaw = open(OLD, ent);
        byte[] bRaw = open(NEW, ent);

        if (aRaw == BINARY || bRaw == BINARY //
                || RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) {
            formatOldNewPaths(buf, ent);
            buf.write(encodeASCII("Binary files differ\n")); //$NON-NLS-1$
            editList = new EditList();
            type = PatchType.BINARY;

        } else {
            res.a = new RawText(aRaw);
            res.b = new RawText(bRaw);
            editList = diff(res.a, res.b);
            type = PatchType.UNIFIED;

            switch (ent.getChangeType()) {
            case RENAME:
            case COPY:
                if (!editList.isEmpty())
                    formatOldNewPaths(buf, ent);
                break;

            default:
                formatOldNewPaths(buf, ent);
                break;
            }
        }
    }

    res.header = new FileHeader(buf.toByteArray(), editList, type);
    return res;
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private void formatHeader(ByteArrayOutputStream o, DiffEntry ent) throws IOException {
    final ChangeType type = ent.getChangeType();
    final String oldp = ent.getOldPath();
    final String newp = ent.getNewPath();
    final FileMode oldMode = ent.getOldMode();
    final FileMode newMode = ent.getNewMode();

    formatGitDiffFirstHeaderLine(o, type, oldp, newp);

    if ((type == MODIFY || type == COPY || type == RENAME) && !oldMode.equals(newMode)) {
        o.write(encodeASCII("old mode ")); //$NON-NLS-1$
        oldMode.copyTo(o);/*from   w  w  w  . java  2 s . c  om*/
        o.write('\n');

        o.write(encodeASCII("new mode ")); //$NON-NLS-1$
        newMode.copyTo(o);
        o.write('\n');
    }

    switch (type) {
    case ADD:
        o.write(encodeASCII("new file mode ")); //$NON-NLS-1$
        newMode.copyTo(o);
        o.write('\n');
        break;

    case DELETE:
        o.write(encodeASCII("deleted file mode ")); //$NON-NLS-1$
        oldMode.copyTo(o);
        o.write('\n');
        break;

    case RENAME:
        o.write(encodeASCII("similarity index " + ent.getScore() + "%")); //$NON-NLS-1$ //$NON-NLS-2$
        o.write('\n');

        o.write(encode("rename from " + quotePath(oldp))); //$NON-NLS-1$
        o.write('\n');

        o.write(encode("rename to " + quotePath(newp))); //$NON-NLS-1$
        o.write('\n');
        break;

    case COPY:
        o.write(encodeASCII("similarity index " + ent.getScore() + "%")); //$NON-NLS-1$ //$NON-NLS-2$
        o.write('\n');

        o.write(encode("copy from " + quotePath(oldp))); //$NON-NLS-1$
        o.write('\n');

        o.write(encode("copy to " + quotePath(newp))); //$NON-NLS-1$
        o.write('\n');
        break;

    case MODIFY:
        if (0 < ent.getScore()) {
            o.write(encodeASCII("dissimilarity index " //$NON-NLS-1$
                    + (100 - ent.getScore()) + "%")); //$NON-NLS-1$
            o.write('\n');
        }
        break;
    }

    if (ent.getOldId() != null && !ent.getOldId().equals(ent.getNewId())) {
        formatIndexLine(o, ent);
    }
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

/**
 * @param o   the stream the formatter will write line data to
 * @param ent the DiffEntry to create the FileHeader for
 * @throws IOException writing to the supplied stream failed.
 *//* w  w  w.j a v  a  2  s  .  c o  m*/
protected void formatIndexLine(OutputStream o, DiffEntry ent) throws IOException {
    o.write(encodeASCII("index " // //$NON-NLS-1$
            + format(ent.getOldId()) //
            + ".." // //$NON-NLS-1$
            + format(ent.getNewId())));
    if (ent.getOldMode().equals(ent.getNewMode())) {
        o.write(' ');
        ent.getNewMode().copyTo(o);
    }
    o.write('\n');
}

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private void formatOldNewPaths(ByteArrayOutputStream o, DiffEntry ent) throws IOException {
    if (ent.getOldId().equals(ent.getNewId()))
        return;//  w  w w. j a  va 2 s  .  c o m

    final String oldp;
    final String newp;

    switch (ent.getChangeType()) {
    case ADD:
        oldp = DiffEntry.DEV_NULL;
        newp = quotePath(newPrefix + ent.getNewPath());
        break;

    case DELETE:
        oldp = quotePath(oldPrefix + ent.getOldPath());
        newp = DiffEntry.DEV_NULL;
        break;

    default:
        oldp = quotePath(oldPrefix + ent.getOldPath());
        newp = quotePath(newPrefix + ent.getNewPath());
        break;
    }

    o.write(encode("--- " + oldp + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
    o.write(encode("+++ " + newp + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

/**
 * loads all patches of from the given list of {@link DiffEntry}s.
 * //from  w  w  w .  j a  v a2s .  c  o  m
 * @param patchSet
 *            the patchSet to add the patches to.
 * @param ref
 *            the ref to the commit of the patch set.
 * @param repository
 *            the git repository instance
 * @throws RepositoryIOException
 */
private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException {

    EList<Patch> patches = patchSet.getPatches();
    Repository repository = git.getRepository();

    try {

        RevWalk revWalk = new RevWalk(repository);
        RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
        RevCommit oldCommit = newCommit.getParent(0);
        revWalk.parseHeaders(oldCommit);
        ObjectReader objectReader = repository.newObjectReader();
        revWalk.close();

        CanonicalTreeParser newTreeIterator = new CanonicalTreeParser();
        newTreeIterator.reset(objectReader, newCommit.getTree().getId());
        CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser();
        oldTreeIterator.reset(objectReader, oldCommit.getTree().getId());

        List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call();

        for (DiffEntry diff : diffs) {

            String newPath = diff.getNewPath();
            String oldPath = diff.getOldPath();
            Patch patch = null;

            /*
             * only papyrus diagrams are supported for now, so models are in
             * .uml files, diagrams in .notation files
             */

            if (diff.getChangeType() != ChangeType.DELETE) {
                if (newPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (newPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            } else {
                if (oldPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (oldPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            }

            switch (diff.getChangeType()) {
            case ADD:
                patch.setChangeType(PatchChangeType.ADD);
                break;
            case COPY:
                patch.setChangeType(PatchChangeType.COPY);
                break;
            case DELETE:
                patch.setChangeType(PatchChangeType.DELETE);
                break;
            case MODIFY:
                patch.setChangeType(PatchChangeType.MODIFY);
                break;
            case RENAME:
                patch.setChangeType(PatchChangeType.RENAME);
                break;
            }

            patch.setNewPath(newPath);
            patch.setOldPath(oldPath);

            if (diff.getChangeType() != ChangeType.DELETE) {
                ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId());
                patch.setNewContent(objectLoader.getBytes());
            }
            if (diff.getChangeType() != ChangeType.ADD) {
                ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId());
                patch.setOldContent(objectLoader.getBytes());
            }
            patches.add(patch);

        }

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e);
    } catch (GitAPIException e) {
        throw new RepositoryIOException(
                MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}",
                        patchSet.getId()),
                e);
    }
}

From source file:com.buildautomation.jgit.api.ShowFileDiff.java

License:Apache License

public static void showFileDiff() throws IOException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        // the diff works on TreeIterators, we prepare two for the two branches
        AbstractTreeIterator oldTreeParser = prepareTreeParser(repository,
                "09c65401f3730eb3e619c33bf31e2376fb393727");
        AbstractTreeIterator newTreeParser = prepareTreeParser(repository,
                "aa31703b65774e4a06010824601e56375a70078c");

        // then the procelain diff-command returns a list of diff entries
        try (Git git = new Git(repository)) {
            List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser)
                    .setPathFilter(PathFilter.create("README.md")).call();
            for (DiffEntry entry : diff) {
                System.out.println(
                        "Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
                try (DiffFormatter formatter = new DiffFormatter(System.out)) {
                    formatter.setRepository(repository);
                    formatter.format(entry);
                }/*  w  ww.  j  a  va  2s .c o  m*/
            }
        }
    }
}

From source file:com.gitblit.utils.GitBlitDiffFormatter.java

License:Apache License

@Override
public void format(DiffEntry ent) throws IOException {
    currentPath = diffStat.addPath(ent);
    nofLinesCurrent = 0;/*from w  w w . j a  v  a 2s .  c o  m*/
    isOff = false;
    entry = ent;
    if (!truncated) {
        totalNofLinesPrevious = totalNofLinesCurrent;
        if (globalDiffLimit > 0 && totalNofLinesPrevious > globalDiffLimit) {
            truncated = true;
            isOff = true;
        }
        truncateTo = os.size();
    } else {
        isOff = true;
    }
    if (truncated) {
        skipped.add(ent);
    } else {
        // Produce a header here and now
        String path;
        String id;
        if (ChangeType.DELETE.equals(ent.getChangeType())) {
            path = ent.getOldPath();
            id = ent.getOldId().name();
        } else {
            path = ent.getNewPath();
            id = ent.getNewId().name();
        }
        StringBuilder sb = new StringBuilder(MessageFormat.format(
                "<div class='header'><div class=\"diffHeader\" id=\"n{0}\"><i class=\"icon-file\"></i> ", id));
        sb.append(StringUtils.escapeForHtml(path, false)).append("</div></div>");
        sb.append("<div class=\"diff\"><table cellpadding='0'><tbody>\n");
        os.write(sb.toString().getBytes());
    }
    // Keep formatting, but if off, don't produce anything anymore. We just keep on counting.
    super.format(ent);
    if (!truncated) {
        // Close the table
        os.write("</tbody></table></div>\n".getBytes());
    }
}

From source file:com.gitblit.utils.GitBlitDiffFormatter.java

License:Apache License

/**
 * Workaround function for complex private methods in DiffFormatter. This sets the html for the diff headers.
 *
 * @return/*from  ww  w. ja  va  2s  .  c om*/
 */
public String getHtml() {
    String html = RawParseUtils.decode(os.toByteArray());
    String[] lines = html.split("\n");
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
        if (line.startsWith("index") || line.startsWith("similarity") || line.startsWith("rename from ")
                || line.startsWith("rename to ")) {
            // skip index lines
        } else if (line.startsWith("new file") || line.startsWith("deleted file")) {
            // skip new file lines
        } else if (line.startsWith("\\ No newline")) {
            // skip no new line
        } else if (line.startsWith("---") || line.startsWith("+++")) {
            // skip --- +++ lines
        } else if (line.startsWith("diff")) {
            // skip diff lines
        } else {
            boolean gitLinkDiff = line.length() > 0 && line.substring(1).startsWith("Subproject commit");
            if (gitLinkDiff) {
                sb.append("<tr><th class='diff-line'></th><th class='diff-line'></th>");
                if (line.charAt(0) == '+') {
                    sb.append("<th class='diff-state diff-state-add'></th><td class=\"diff-cell add2\">");
                } else {
                    sb.append("<th class='diff-state diff-state-sub'></th><td class=\"diff-cell remove2\">");
                }
                line = StringUtils.escapeForHtml(line.substring(1), CONVERT_TABS, tabLength);
            }
            sb.append(line);
            if (gitLinkDiff) {
                sb.append("</td></tr>");
            }
            sb.append('\n');
        }
    }
    if (truncated) {
        sb.append(MessageFormat.format("<div class='header'><div class='diffHeader'>{0}</div></div>",
                StringUtils.escapeForHtml(getMsg("gb.diffTruncated", "Diff truncated after the above file"),
                        false)));
        // List all files not shown. We can be sure we do have at least one path in skipped.
        sb.append("<div class='diff'><table cellpadding='0'><tbody><tr><td class='diff-cell' colspan='4'>");
        String deletedSuffix = StringUtils.escapeForHtml(getMsg("gb.diffDeletedFileSkipped", "(deleted)"),
                false);
        boolean first = true;
        for (DiffEntry entry : skipped) {
            if (!first) {
                sb.append('\n');
            }
            if (ChangeType.DELETE.equals(entry.getChangeType())) {
                sb.append("<span id=\"n" + entry.getOldId().name() + "\">"
                        + StringUtils.escapeForHtml(entry.getOldPath(), false) + ' ' + deletedSuffix
                        + "</span>");
            } else {
                sb.append("<span id=\"n" + entry.getNewId().name() + "\">"
                        + StringUtils.escapeForHtml(entry.getNewPath(), false) + "</span>");
            }
            first = false;
        }
        skipped.clear();
        sb.append("</td></tr></tbody></table></div>");
    }
    return sb.toString();
}