Example usage for org.eclipse.jgit.patch FileHeader getHunks

List of usage examples for org.eclipse.jgit.patch FileHeader getHunks

Introduction

In this page you can find the example usage for org.eclipse.jgit.patch FileHeader getHunks.

Prototype

public List<? extends HunkHeader> getHunks() 

Source Link

Document

Get hunks altering this file; in order of appearance in patch

Usage

From source file:MySmartApply.java

License:Eclipse Distribution License

/**
 * @param f//from  w w w  .  ja v a2 s.co m
 * @param fh
 * @throws IOException
 * @throws PatchApplyException
 */
private void apply(File f, FileHeader fh) throws IOException, PatchApplyException {

    if (failed_files.contains(f))
        return;

    RawText rt = new RawText(f);

    List<String> oldLines = new ArrayList<String>(rt.size());

    for (int i = 0; i < rt.size(); i++)
        oldLines.add(rt.getString(i));

    List<String> newLines = new ArrayList<String>(oldLines);

    for (HunkHeader hh : fh.getHunks()) {
        StringBuilder hunk = new StringBuilder();

        for (int j = hh.getStartOffset(); j < hh.getEndOffset(); j++)
            hunk.append((char) hh.getBuffer()[j]);

        RawText hrt = new RawText(hunk.toString().getBytes());

        List<String> hunkLines = new ArrayList<String>(hrt.size());

        for (int i = 0; i < hrt.size(); i++) {
            String line = hrt.getString(i);

            line = removeInvalidChars(line);

            hunkLines.add(line);
        }

        int pos = 0;
        for (int j = 1; j < hunkLines.size(); j++) {

            String hunkLine = hunkLines.get(j);

            // We need the comparison only in case of removing a line or do nothing with it.
            String newLine = null;
            if (hunkLine.charAt(0) == ' ' || hunkLine.charAt(0) == '-')
                newLine = removeInvalidChars(newLines.get(hh.getNewStartLine() - 1 + pos));

            switch (hunkLine.charAt(0)) {

            case ' ':
                if (!newLine.equals(hunkLine.substring(1))) {
                    failed_files.add(f);
                    if (listener != null)
                        listener.failed();
                    return;
                }
                pos++;
                break;
            case '-':
                if (!newLine.equals(hunkLine.substring(1))) {
                    failed_files.add(f);
                    if (listener != null)
                        listener.failed();
                    return;
                }
                newLines.remove(hh.getNewStartLine() - 1 + pos);
                break;
            case '+':
                newLines.add(hh.getNewStartLine() - 1 + pos, hunkLine.substring(1));
                pos++;
                break;
            }
        }
    }

    if (!isNoNewlineAtEndOfFile(fh))
        newLines.add(""); //$NON-NLS-1$
    if (!rt.isMissingNewlineAtEnd())
        oldLines.add(""); //$NON-NLS-1$
    if (!isChanged(oldLines, newLines))
        return; // don't touch the file
    StringBuilder sb = new StringBuilder();
    for (String l : newLines) {
        // don't bother handling line endings - if it was windows, the \r is
        // still there!
        sb.append(l).append('\n');
    }
    sb.deleteCharAt(sb.length() - 1);
    FileWriter fw = new FileWriter(f);
    fw.write(sb.toString());
    fw.close();

    if (listener != null)
        listener.done();
}

From source file:MySmartApply.java

License:Eclipse Distribution License

private boolean isNoNewlineAtEndOfFile(FileHeader fh) {

    // ... ///*ww w  . j  a  v a  2 s. com*/

    if (fh.getHunks().size() == 0)
        return false;

    // ... //

    HunkHeader lastHunk = fh.getHunks().get(fh.getHunks().size() - 1);
    RawText lhrt = new RawText(lastHunk.getBuffer());
    return lhrt.getString(lhrt.size() - 1).equals("\\ No newline at end of file"); //$NON-NLS-1$
}

From source file:com.google.gerrit.server.patch.PatchListEntry.java

License:Apache License

PatchListEntry(final FileHeader hdr, List<Edit> editList) {
    changeType = toChangeType(hdr);//from   w  w w . ja v  a 2 s.  co m
    patchType = toPatchType(hdr);

    switch (changeType) {
    case DELETED:
        oldName = null;
        newName = hdr.getOldPath();
        break;

    case ADDED:
    case MODIFIED:
        oldName = null;
        newName = hdr.getNewPath();
        break;

    case COPIED:
    case RENAMED:
        oldName = hdr.getOldPath();
        newName = hdr.getNewPath();
        break;

    default:
        throw new IllegalArgumentException("Unsupported type " + changeType);
    }

    header = compact(hdr);

    if (hdr instanceof CombinedFileHeader || hdr.getHunks().isEmpty() //
            || hdr.getOldMode() == FileMode.GITLINK || hdr.getNewMode() == FileMode.GITLINK) {
        edits = Collections.emptyList();
    } else {
        edits = Collections.unmodifiableList(editList);
    }

    int ins = 0;
    int del = 0;
    for (Edit e : editList) {
        del += e.getEndA() - e.getBeginA();
        ins += e.getEndB() - e.getBeginB();
    }
    insertions = ins;
    deletions = del;
}

From source file:com.google.gerrit.server.patch.PatchListEntry.java

License:Apache License

private static int end(final FileHeader h) {
    if (h instanceof CombinedFileHeader) {
        return h.getEndOffset();
    }/* www  .j a  v a2  s .  co m*/
    if (!h.getHunks().isEmpty()) {
        return h.getHunks().get(0).getStartOffset();
    }
    return h.getEndOffset();
}

From source file:com.google.gerrit.server.patch.PatchListLoader.java

License:Apache License

private PatchListEntry newEntry(RevTree aTree, FileHeader fileHeader) {
    final FileMode oldMode = fileHeader.getOldMode();
    final FileMode newMode = fileHeader.getNewMode();

    if (oldMode == FileMode.GITLINK || newMode == FileMode.GITLINK) {
        return new PatchListEntry(fileHeader, Collections.<Edit>emptyList());
    }/*from   w w w . j a  v a 2  s.c o  m*/

    if (aTree == null // want combined diff
            || fileHeader.getPatchType() != PatchType.UNIFIED || fileHeader.getHunks().isEmpty()) {
        return new PatchListEntry(fileHeader, Collections.<Edit>emptyList());
    }

    List<Edit> edits = fileHeader.toEditList();
    if (edits.isEmpty()) {
        return new PatchListEntry(fileHeader, Collections.<Edit>emptyList());
    } else {
        return new PatchListEntry(fileHeader, edits);
    }
}

From source file:com.google.gitiles.DiffServletTest.java

License:Apache License

@Test
public void diffFileNoParentsText() throws Exception {
    String contents = "foo\ncontents\n";
    RevCommit c = repo.update("master", repo.commit().add("foo", contents));

    FakeHttpServletRequest req = FakeHttpServletRequest.newRequest();
    req.setPathInfo("/test/+diff/" + c.name() + "^!/foo");
    req.setQueryString("format=TEXT");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.service(req, res);// w  ww. j  a  v a 2  s .c  om

    Patch p = parsePatch(res.getActualBody());
    FileHeader f = getOnlyElement(p.getFiles());
    assertEquals(ChangeType.ADD, f.getChangeType());
    assertEquals(DiffEntry.DEV_NULL, f.getPath(Side.OLD));
    assertEquals("foo", f.getPath(Side.NEW));

    RawText rt = new RawText(contents.getBytes(UTF_8));
    Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList());
    assertEquals(Type.INSERT, e.getType());
    assertEquals(contents, rt.getString(e.getBeginB(), e.getEndB(), false));
}

From source file:com.google.gitiles.DiffServletTest.java

License:Apache License

@Test
public void diffFileOneParentText() throws Exception {
    String contents1 = "foo\n";
    String contents2 = "foo\ncontents\n";
    RevCommit c1 = repo.update("master", repo.commit().add("foo", contents1));
    RevCommit c2 = repo.update("master", repo.commit().parent(c1).add("foo", contents2));

    FakeHttpServletRequest req = FakeHttpServletRequest.newRequest();
    req.setPathInfo("/test/+diff/" + c2.name() + "^!/foo");
    req.setQueryString("format=TEXT");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.service(req, res);//from w ww  .j  a  v a  2  s  .  c o m

    Patch p = parsePatch(res.getActualBody());
    FileHeader f = getOnlyElement(p.getFiles());
    assertEquals(ChangeType.MODIFY, f.getChangeType());
    assertEquals("foo", f.getPath(Side.OLD));
    assertEquals("foo", f.getPath(Side.NEW));

    RawText rt2 = new RawText(contents2.getBytes(UTF_8));
    Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList());
    assertEquals(Type.INSERT, e.getType());
    assertEquals("contents\n", rt2.getString(e.getBeginB(), e.getEndB(), false));
}

From source file:com.google.gitiles.HtmlDiffFormatter.java

License:Open Source License

@Override
public void format(FileHeader hdr, RawText a, RawText b) throws IOException {
    int start = hdr.getStartOffset();
    int end = hdr.getEndOffset();
    if (!hdr.getHunks().isEmpty()) {
        end = hdr.getHunks().get(0).getStartOffset();
    }/*from ww w . ja va  2  s.  c o m*/
    renderHeader(RawParseUtils.decode(hdr.getBuffer(), start, end));

    if (hdr.getPatchType() == PatchType.UNIFIED) {
        getOutputStream().write(DIFF_BEGIN);
        format(hdr.toEditList(), a, b);
        getOutputStream().write(DIFF_END);
    }
}

From source file:com.wirelust.sonar.plugins.bitbucket.PullRequestFacade.java

License:Open Source License

public void loadPatch(PullRequest pullRequest) throws IOException {

    Response response = bitbucketClient.getPullRequestDiff(config.repositoryOwner(), config.repository(),
            pullRequest.getId());/*from  www .  j  av  a  2  s  . c  o m*/
    LOGGER.debug("received bitbucket response getPullRequestDiff:{}", response.getStatus());

    String diffString = response.readEntity(String.class);
    InputStream diffStream = new ByteArrayInputStream(diffString.getBytes(StandardCharsets.UTF_8));

    Patch patch = new Patch();
    patch.parse(diffStream);

    modifiedLinesByFile = new HashMap<>();

    for (FileHeader fileHeader : patch.getFiles()) {
        List<Integer> patchLocationMapping = new ArrayList<>();
        modifiedLinesByFile.put(fileHeader.getNewPath(), patchLocationMapping);

        if (fileHeader.getHunks() != null) {
            loadHeaderHunks(patchLocationMapping, fileHeader);
        }
    }
}

From source file:com.wirelust.sonar.plugins.bitbucket.PullRequestFacade.java

License:Open Source License

private void loadHeaderHunks(List<Integer> patchLocationMapping, FileHeader fileHeader) {
    for (HunkHeader hunk : fileHeader.getHunks()) {
        for (Edit edit : hunk.toEditList()) {
            if (!edit.getType().equals(Edit.Type.DELETE)) {
                for (int line = edit.getBeginB(); line < edit.getEndB(); line++) {
                    patchLocationMapping.add(line + 1);
                }//  w  w w.  j  a va 2 s .c  o m
            }
        }
    }
}