Search in sources :

Example 81 with Edit

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

the class PatchScriptBuilder method ensureCommentsVisible.

private void ensureCommentsVisible(final CommentDetail comments) {
    if (comments.getCommentsA().isEmpty() && comments.getCommentsB().isEmpty()) {
        //
        return;
    }
    // Construct empty Edit blocks around each location where a comment is.
    // This will force the later packContent method to include the regions
    // containing comments, potentially combining those regions together if
    // they have overlapping contexts. UI renders will also be able to make
    // correct hunks from this, but because the Edit is empty they will not
    // style it specially.
    //
    final List<Edit> empty = new ArrayList<>();
    int lastLine;
    lastLine = -1;
    for (Comment c : comments.getCommentsA()) {
        final int a = c.lineNbr;
        if (lastLine != a) {
            final int b = mapA2B(a - 1);
            if (0 <= b) {
                safeAdd(empty, new Edit(a - 1, b));
            }
            lastLine = a;
        }
    }
    lastLine = -1;
    for (Comment c : comments.getCommentsB()) {
        int b = c.lineNbr;
        if (lastLine != b) {
            final int a = mapB2A(b - 1);
            if (0 <= a) {
                safeAdd(empty, new Edit(a, b - 1));
            }
            lastLine = b;
        }
    }
    // Sort the final list by the index in A, so packContent can combine
    // them correctly later.
    //
    edits.addAll(empty);
    Collections.sort(edits, EDIT_SORT);
}
Also used : Comment(com.google.gerrit.reviewdb.client.Comment) ArrayList(java.util.ArrayList) Edit(org.eclipse.jgit.diff.Edit)

Example 82 with Edit

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

the class GetDiff method apply.

@Override
public Response<DiffInfo> apply(FileResource resource) throws ResourceConflictException, ResourceNotFoundException, OrmException, AuthException, InvalidChangeOperationException, IOException {
    DiffPreferencesInfo prefs = new DiffPreferencesInfo();
    if (whitespace != null) {
        prefs.ignoreWhitespace = whitespace;
    } else if (ignoreWhitespace != null) {
        prefs.ignoreWhitespace = ignoreWhitespace.whitespace;
    } else {
        prefs.ignoreWhitespace = Whitespace.IGNORE_LEADING_AND_TRAILING;
    }
    prefs.context = context;
    prefs.intralineDifference = intraline;
    PatchScriptFactory psf;
    PatchSet basePatchSet = null;
    if (base != null) {
        RevisionResource baseResource = revisions.parse(resource.getRevision().getChangeResource(), IdString.fromDecoded(base));
        basePatchSet = baseResource.getPatchSet();
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), basePatchSet.getId(), resource.getPatchKey().getParentKey(), prefs);
    } else if (parentNum > 0) {
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), parentNum - 1, resource.getPatchKey().getParentKey(), prefs);
    } else {
        psf = patchScriptFactoryFactory.create(resource.getRevision().getControl(), resource.getPatchKey().getFileName(), null, resource.getPatchKey().getParentKey(), prefs);
    }
    try {
        psf.setLoadHistory(false);
        psf.setLoadComments(context != DiffPreferencesInfo.WHOLE_FILE_CONTEXT);
        PatchScript ps = psf.call();
        Content content = new Content(ps);
        for (Edit edit : ps.getEdits()) {
            if (edit.getType() == Edit.Type.EMPTY) {
                continue;
            }
            content.addCommon(edit.getBeginA());
            checkState(content.nextA == edit.getBeginA(), "nextA = %s; want %s", content.nextA, edit.getBeginA());
            checkState(content.nextB == edit.getBeginB(), "nextB = %s; want %s", content.nextB, edit.getBeginB());
            switch(edit.getType()) {
                case DELETE:
                case INSERT:
                case REPLACE:
                    List<Edit> internalEdit = edit instanceof ReplaceEdit ? ((ReplaceEdit) edit).getInternalEdits() : null;
                    content.addDiff(edit.getEndA(), edit.getEndB(), internalEdit);
                    break;
                case EMPTY:
                default:
                    throw new IllegalStateException();
            }
        }
        content.addCommon(ps.getA().size());
        ProjectState state = projectCache.get(resource.getRevision().getChange().getProject());
        DiffInfo result = new DiffInfo();
        // TODO referring to the parent commit by refs/changes/12/60012/1^1
        // will likely not work for inline edits
        String revA = basePatchSet != null ? basePatchSet.getRefName() : resource.getRevision().getPatchSet().getRefName() + "^1";
        String revB = resource.getRevision().getEdit().isPresent() ? resource.getRevision().getEdit().get().getRefName() : resource.getRevision().getPatchSet().getRefName();
        List<DiffWebLinkInfo> links = webLinks.getDiffLinks(state.getProject().getName(), resource.getPatchKey().getParentKey().getParentKey().get(), basePatchSet != null ? basePatchSet.getId().get() : null, revA, MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName()), resource.getPatchKey().getParentKey().get(), revB, ps.getNewName());
        result.webLinks = links.isEmpty() ? null : links;
        if (!webLinksOnly) {
            if (ps.isBinary()) {
                result.binary = true;
            }
            if (ps.getDisplayMethodA() != DisplayMethod.NONE) {
                result.metaA = new FileMeta();
                result.metaA.name = MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName());
                result.metaA.contentType = FileContentUtil.resolveContentType(state, result.metaA.name, ps.getFileModeA(), ps.getMimeTypeA());
                result.metaA.lines = ps.getA().size();
                result.metaA.webLinks = getFileWebLinks(state.getProject(), revA, result.metaA.name);
                result.metaA.commitId = content.commitIdA;
            }
            if (ps.getDisplayMethodB() != DisplayMethod.NONE) {
                result.metaB = new FileMeta();
                result.metaB.name = ps.getNewName();
                result.metaB.contentType = FileContentUtil.resolveContentType(state, result.metaB.name, ps.getFileModeB(), ps.getMimeTypeB());
                result.metaB.lines = ps.getB().size();
                result.metaB.webLinks = getFileWebLinks(state.getProject(), revB, result.metaB.name);
                result.metaB.commitId = content.commitIdB;
            }
            if (intraline) {
                if (ps.hasIntralineTimeout()) {
                    result.intralineStatus = IntraLineStatus.TIMEOUT;
                } else if (ps.hasIntralineFailure()) {
                    result.intralineStatus = IntraLineStatus.FAILURE;
                } else {
                    result.intralineStatus = IntraLineStatus.OK;
                }
            }
            result.changeType = CHANGE_TYPE.get(ps.getChangeType());
            if (result.changeType == null) {
                throw new IllegalStateException("unknown change type: " + ps.getChangeType());
            }
            if (ps.getPatchHeader().size() > 0) {
                result.diffHeader = ps.getPatchHeader();
            }
            result.content = content.lines;
        }
        Response<DiffInfo> r = Response.ok(result);
        if (resource.isCacheable()) {
            r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
        }
        return r;
    } catch (NoSuchChangeException e) {
        throw new ResourceNotFoundException(e.getMessage(), e);
    } catch (LargeObjectException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
}
Also used : PatchScript(com.google.gerrit.common.data.PatchScript) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) ReplaceEdit(org.eclipse.jgit.diff.ReplaceEdit) Edit(org.eclipse.jgit.diff.Edit) IdString(com.google.gerrit.extensions.restapi.IdString) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) DiffWebLinkInfo(com.google.gerrit.extensions.common.DiffWebLinkInfo) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) PatchScriptFactory(com.google.gerrit.server.patch.PatchScriptFactory) SparseFileContent(com.google.gerrit.prettify.common.SparseFileContent) ReplaceEdit(org.eclipse.jgit.diff.ReplaceEdit) ProjectState(com.google.gerrit.server.project.ProjectState) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) FileMeta(com.google.gerrit.extensions.common.DiffInfo.FileMeta) DiffInfo(com.google.gerrit.extensions.common.DiffInfo)

Example 83 with Edit

use of org.eclipse.jgit.diff.Edit 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 84 with Edit

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

the class DiffUtils method diff.

private static void diff(Git git, ObjectReader reader, DiffEntry diff, Writer result) throws IOException {
    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(diff);
    // System.out.println(new String(baos.toByteArray()));
    AbbreviatedObjectId id1 = diff.getOldId();
    AbbreviatedObjectId id2 = diff.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) {
            result.write("<div class=\"edit unchanged\">");
        }
        while (aCur < curEdit.getBeginA()) {
            result.write(html(rt1.getString(aCur++)) + "\n");
        }
        if (prolog) {
            result.write("</div>");
        }
        if (curEdit.getType() == Edit.Type.INSERT) {
            result.write("<div class=\"edit added\">");
            for (int i = curEdit.getBeginB(); i < curEdit.getEndB(); i++) {
                result.write(html(rt2.getString(i)) + "\n");
            }
            result.write("</div>");
        }
        if (curEdit.getType() == Edit.Type.REPLACE) {
            result.write("<div class=\"edit changed\"><div class=\"edit removed\">");
            for (int i = curEdit.getBeginA(); i < curEdit.getEndA(); i++) {
                result.write(html(rt1.getString(i)) + "\n");
            }
            result.write("</div><div class=\"edit added\">");
            for (int i = curEdit.getBeginB(); i < curEdit.getEndB(); i++) {
                result.write(html(rt2.getString(i)) + "\n");
            }
            aCur = curEdit.getEndA();
            result.write("</div></div>");
        }
        if (curEdit.getType() == Edit.Type.DELETE) {
            result.write("<div class=\"edit changed\"><div class=\"edit removed\">");
            for (int i = curEdit.getBeginA(); i < curEdit.getEndA(); i++) {
                result.write(html(rt1.getString(i)) + "\n");
            }
            aCur = curEdit.getEndA();
            result.write("</div></div>");
        }
    }
    boolean prolog = aCur < rt1.size();
    if (prolog) {
        result.write("<div class=\"edit unchanged\">");
    }
    while (aCur < rt1.size()) {
        result.write(html(rt1.getString(aCur++)) + "\n");
    }
    if (prolog) {
        result.write("</div>");
    }
}
Also used : AbbreviatedObjectId(org.eclipse.jgit.lib.AbbreviatedObjectId) Edit(org.eclipse.jgit.diff.Edit) ByteArrayOutputStream(java.io.ByteArrayOutputStream) EditList(org.eclipse.jgit.diff.EditList) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) RawText(org.eclipse.jgit.diff.RawText)

Example 85 with Edit

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

the class DiffContentCalculator method correctForDifferencesInNewlineAtEnd.

private ImmutableList<Edit> correctForDifferencesInNewlineAtEnd(TextSource a, TextSource b, ImmutableList<Edit> edits) {
    // a.src.size() is the size ignoring a newline at the end whereas a.size() considers it.
    int aSize = a.src.size();
    int bSize = b.src.size();
    if (edits.isEmpty() && (aSize == 0 || bSize == 0)) {
        // renamed file looks like a deletion).
        return edits;
    }
    if (edits.isEmpty() && (aSize != bSize)) {
        // code which later assembles the file contents would fail.
        return edits;
    }
    Optional<Edit> lastEdit = getLast(edits);
    if (isNewlineAtEndDeleted(a, b)) {
        Optional<Edit> lastLineEdit = lastEdit.filter(edit -> edit.getEndA() == aSize);
        if (lastLineEdit.isPresent()) {
            Edit edit = lastLineEdit.get();
            Edit updatedLastLineEdit = edit instanceof ReplaceEdit ? new ReplaceEdit(edit.getBeginA(), edit.getEndA() + 1, edit.getBeginB(), edit.getEndB(), ((ReplaceEdit) edit).getInternalEdits()) : new Edit(edit.getBeginA(), edit.getEndA() + 1, edit.getBeginB(), edit.getEndB());
            ImmutableList.Builder<Edit> newEditsBuilder = ImmutableList.builderWithExpectedSize(edits.size());
            return newEditsBuilder.addAll(edits.subList(0, edits.size() - 1)).add(updatedLastLineEdit).build();
        }
        ImmutableList.Builder<Edit> newEditsBuilder = ImmutableList.builderWithExpectedSize(edits.size() + 1);
        Edit newlineEdit = new Edit(aSize, aSize + 1, bSize, bSize);
        return newEditsBuilder.addAll(edits).add(newlineEdit).build();
    } else if (isNewlineAtEndAdded(a, b)) {
        Optional<Edit> lastLineEdit = lastEdit.filter(edit -> edit.getEndB() == bSize);
        if (lastLineEdit.isPresent()) {
            Edit edit = lastLineEdit.get();
            Edit updatedLastLineEdit = edit instanceof ReplaceEdit ? new ReplaceEdit(edit.getBeginA(), edit.getEndA(), edit.getBeginB(), edit.getEndB() + 1, ((ReplaceEdit) edit).getInternalEdits()) : new Edit(edit.getBeginA(), edit.getEndA(), edit.getBeginB(), edit.getEndB() + 1);
            ImmutableList.Builder<Edit> newEditsBuilder = ImmutableList.builderWithExpectedSize(edits.size());
            return newEditsBuilder.addAll(edits.subList(0, edits.size() - 1)).add(updatedLastLineEdit).build();
        }
        ImmutableList.Builder<Edit> newEditsBuilder = ImmutableList.builderWithExpectedSize(edits.size() + 1);
        Edit newlineEdit = new Edit(aSize, aSize, bSize, bSize + 1);
        return newEditsBuilder.addAll(edits).add(newlineEdit).build();
    }
    return edits;
}
Also used : SparseFileContentBuilder(com.google.gerrit.prettify.common.SparseFileContentBuilder) List(java.util.List) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) ImmutableList(com.google.common.collect.ImmutableList) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) Edit(org.eclipse.jgit.diff.Edit) ReplaceEdit(com.google.gerrit.jgit.diff.ReplaceEdit) Optional(java.util.Optional) EditHunk(com.google.gerrit.prettify.common.EditHunk) SparseFileContent(com.google.gerrit.prettify.common.SparseFileContent) Optional(java.util.Optional) ImmutableList(com.google.common.collect.ImmutableList) SparseFileContentBuilder(com.google.gerrit.prettify.common.SparseFileContentBuilder) ReplaceEdit(com.google.gerrit.jgit.diff.ReplaceEdit) Edit(org.eclipse.jgit.diff.Edit) ReplaceEdit(com.google.gerrit.jgit.diff.ReplaceEdit)

Aggregations

Edit (org.eclipse.jgit.diff.Edit)142 Test (org.junit.Test)117 FixResult (com.google.gerrit.server.fixes.FixCalculator.FixResult)112 ReplaceEdit (com.google.gerrit.jgit.diff.ReplaceEdit)9 ArrayList (java.util.ArrayList)5 RawText (org.eclipse.jgit.diff.RawText)5 Range (com.google.gerrit.entities.Comment.Range)4 FixReplacement (com.google.gerrit.entities.FixReplacement)4 Text (com.google.gerrit.server.patch.Text)4 EditList (org.eclipse.jgit.diff.EditList)4 PatchScript (com.google.gerrit.common.data.PatchScript)3 TaggedEdit (com.google.gerrit.server.patch.filediff.TaggedEdit)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)3 ReplaceEdit (org.eclipse.jgit.diff.ReplaceEdit)3 AbbreviatedObjectId (org.eclipse.jgit.lib.AbbreviatedObjectId)3 ObjectReader (org.eclipse.jgit.lib.ObjectReader)3 RevWalk (org.eclipse.jgit.revwalk.RevWalk)3 DiffPreferencesInfo (com.google.gerrit.extensions.client.DiffPreferencesInfo)2 SparseFileContent (com.google.gerrit.prettify.common.SparseFileContent)2