Example usage for org.eclipse.jgit.patch Patch getFiles

List of usage examples for org.eclipse.jgit.patch Patch getFiles

Introduction

In this page you can find the example usage for org.eclipse.jgit.patch Patch getFiles.

Prototype

public List<? extends FileHeader> getFiles() 

Source Link

Document

Get list of files described in the patch, in occurrence order.

Usage

From source file:MySmartApply.java

License:Eclipse Distribution License

/**
 * Executes the {@code ApplyCommand} command with all the options and
 * parameters collected by the setter methods (e.g.
 * {@link #setPatch(InputStream)} of this class. Each instance of this class
 * should only be used for one invocation of the command. Don't call this
 * method twice on an instance./*from  ww  w  .j  a  v a  2 s. c  om*/
 *
 * @return an {@link ApplyResult} object representing the command result
 * @throws GitAPIException
 * @throws PatchFormatException
 * @throws PatchApplyException
 */
public ApplyResult call() throws GitAPIException, PatchFormatException, PatchApplyException {
    ApplyResult r = new ApplyResult();
    try {
        final Patch p = new Patch();
        try {
            p.parse(in);
        } finally {
            in.close();
        }
        if (!p.getErrors().isEmpty())
            throw new PatchFormatException(p.getErrors());
        for (FileHeader fh : p.getFiles()) {

            if (listener != null)
                listener.setFilename(
                        getFile((fh.getChangeType() != ChangeType.ADD) ? fh.getOldPath() : fh.getNewPath(),
                                false).getName());

            if (fh.getChangeType() == ChangeType.ADD || fh.getChangeType() == ChangeType.MODIFY
                    || fh.getChangeType() == ChangeType.COPY) {
                if (fh.getNewPath().contains(".lang.php") || fh.getNewPath().contains(".gitignore")
                        || fh.getNewPath().equals("includes/config.php")
                        || fh.getNewPath().contains("/images")) {
                    if (fh.getNewPath().contains(".lang.php") || fh.getNewPath().contains("/images"))
                        this.failed_files.add(getFile(
                                (fh.getChangeType() != ChangeType.ADD) ? fh.getOldPath() : fh.getNewPath(),
                                false));

                    if (listener != null)
                        listener.skipped();
                    continue;
                }
            }

            if (listener != null)
                listener.started();

            ChangeType type = fh.getChangeType();
            File f = null;
            switch (type) {
            case ADD:
                f = getFile(fh.getNewPath(), true);
                apply(f, fh);
                break;
            case MODIFY:
                f = getFile(fh.getOldPath(), false);
                apply(f, fh);
                break;
            case DELETE:
                f = getFile(fh.getOldPath(), false);
                if (!f.delete())
                    throw new PatchApplyException(MessageFormat.format(JGitText.get().cannotDeleteFile, f));
                break;
            case RENAME:
                f = getFile(fh.getOldPath(), false);
                File dest = getFile(fh.getNewPath(), false);
                if (!f.renameTo(dest))
                    throw new PatchApplyException(
                            MessageFormat.format(JGitText.get().renameFileFailed, f, dest));
                break;
            case COPY:
                f = getFile(fh.getOldPath(), false);
                byte[] bs = IO.readFully(f);
                FileOutputStream fos = new FileOutputStream(getFile(fh.getNewPath(), true));
                try {
                    fos.write(bs);
                } finally {
                    fos.close();
                }
            }

            // ... //

            if (!failed_files.contains(f) && type != ChangeType.DELETE)
                r.addUpdatedFile(f);

            // ... //
        }
    } catch (IOException e) {
        throw new PatchApplyException(MessageFormat.format(JGitText.get().patchApplyException, e.getMessage()),
                e);
    }

    return r;
}

From source file:com.github.rwhogg.git_vcr.Util.java

License:Open Source License

/**
 * getFilesChanged returns a list of all the files changed by this patch
 * @param patch The patch to check/*from  w w w  . jav a2s .  co  m*/
 * @return a list of pairs of files changed (first is the old path, second is the new path)
 */
public static List<ImmutablePair<String, String>> getFilesChanged(Patch patch) {
    List<ImmutablePair<String, String>> changeList = new LinkedList<>();
    List<? extends FileHeader> headers = patch.getFiles();
    for (FileHeader header : headers) {
        ImmutablePair<String, String> pair = new ImmutablePair<>(header.getOldPath(), header.getNewPath());
        changeList.add(pair);
    }
    return changeList;
}

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);/*from  w w  w . j  a v a2s  . c o  m*/

    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  w  w .ja  v a2s.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.DiffServletTest.java

License:Apache License

@Test
public void diffDirectoryText() throws Exception {
    String contents = "contents\n";
    RevCommit c = repo.update("master",
            repo.commit().add("dir/foo", contents).add("dir/bar", contents).add("baz", contents));

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

    Patch p = parsePatch(res.getActualBody());
    assertEquals(2, p.getFiles().size());
    assertEquals("dir/bar", p.getFiles().get(0).getPath(Side.NEW));
    assertEquals("dir/foo", p.getFiles().get(1).getPath(Side.NEW));
}

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());//  w  w w . ja  v  a2  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.PullRequestFacadeTest.java

License:Open Source License

@Test
public void testLoadingUnifiedDiff() throws IOException {

    InputStream diffStream = getClass().getClassLoader().getResourceAsStream("unified_diff.txt");

    Patch patch = new Patch();
    patch.parse(diffStream);// w  ww  . j  a  va2s.  co m

    for (FileHeader fileHeader : patch.getFiles()) {
        for (HunkHeader hunk : fileHeader.getHunks()) {
            hunk.toEditList();
        }
    }

    assertThat(patch.getFiles().size() == 7).isTrue();
}

From source file:de.codesourcery.gittimelapse.TextFile.java

License:Apache License

public void forwardsPatchAndAlign(Patch patch) throws IOException, PatchApplyException {
    if (patch.getFiles().size() != 1) {
        throw new IllegalArgumentException("Patch needs to contain exactly 1 FileHeader");
    }/*from  w  w w.j  a va  2s .co  m*/
    final FileHeader fh = patch.getFiles().get(0);

    final List<String> oldLines = new ArrayList<String>(rawText.size());
    for (int i = 0; i < rawText.size(); i++) {
        oldLines.add(rawText.getString(i));
    }

    final List<String> newLines = new ArrayList<String>(oldLines);
    for (final HunkHeader hunkHeader : fh.getHunks()) {
        final StringBuilder hunk = new StringBuilder();
        for (int j = hunkHeader.getStartOffset(); j < hunkHeader.getEndOffset(); j++) {
            hunk.append((char) hunkHeader.getBuffer()[j]);
        }

        final RawText hunkRawText = new RawText(hunk.toString().getBytes());

        final List<String> hunkLines = new ArrayList<String>(hunkRawText.size());
        for (int i = 0; i < hunkRawText.size(); i++) {
            hunkLines.add(hunkRawText.getString(i));
        }

        int pos = 0;
        for (int j = 1; j < hunkLines.size(); j++) {
            final String hunkLine = hunkLines.get(j);
            switch (hunkLine.charAt(0)) {
            case ' ': // context line
                pos++;
                break;
            case '-': // line removed
                changesByLine.put(hunkHeader.getNewStartLine() - 1 + pos, ChangeType.DELETED);
                pos++;
                break;
            case '+': // line added
                changesByLine.put(hunkHeader.getNewStartLine() - 1 + pos, ChangeType.ADDED);
                newLines.add(hunkHeader.getNewStartLine() - 1 + pos, "               "); // JTextPane uses a colored background so we need to have SOMETHING on this line
                pos++;
                break;
            }
        }
    }
    if (!isNoNewlineAtEndOfFile(fh)) {
        newLines.add(""); //$NON-NLS-1$
    }
    if (!rawText.isMissingNewlineAtEnd()) {
        oldLines.add(""); //$NON-NLS-1$
    }
    final StringBuilder sb = new StringBuilder();
    for (final 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);
    setText(sb.toString());
}

From source file:de.codesourcery.gittimelapse.TextFile.java

License:Apache License

public void backwardsPatchAndAlign(Patch patch) throws IOException, PatchApplyException {
    if (patch.getFiles().size() != 1) {
        throw new IllegalArgumentException("Patch needs to contain exactly one FileHeader");
    }/*from w  w w.  j  a v a2  s .  c  om*/

    final FileHeader fh = patch.getFiles().get(0);
    final List<String> oldLines = new ArrayList<String>(rawText.size());
    for (int i = 0; i < rawText.size(); i++) {
        oldLines.add(rawText.getString(i));
    }

    final List<String> newLines = new ArrayList<String>(oldLines);
    for (final HunkHeader hunkHeader : fh.getHunks()) {
        final StringBuilder hunk = new StringBuilder();
        for (int j = hunkHeader.getStartOffset(); j < hunkHeader.getEndOffset(); j++) {
            hunk.append((char) hunkHeader.getBuffer()[j]);
        }

        final RawText hunkRawText = new RawText(hunk.toString().getBytes());

        final List<String> hunkLines = new ArrayList<String>(hunkRawText.size());
        for (int i = 0; i < hunkRawText.size(); i++) {
            hunkLines.add(hunkRawText.getString(i));
        }

        int pos = 0;
        for (int j = 1; j < hunkLines.size(); j++) {
            final String hunkLine = hunkLines.get(j);
            switch (hunkLine.charAt(0)) {
            case ' ':
                pos++;
                break;
            case '+':
                changesByLine.put(hunkHeader.getNewStartLine() - 1 + pos, ChangeType.DELETED);
                newLines.add(hunkHeader.getNewStartLine() - 1 + pos, "               ");
                pos++;
                break;
            case '-':
                changesByLine.put(hunkHeader.getNewStartLine() - 1 + pos, ChangeType.ADDED);
                pos++;
                break;
            }
        }
    }
    if (!isNoNewlineAtEndOfFile(fh)) {
        newLines.add(""); //$NON-NLS-1$
    }
    if (!rawText.isMissingNewlineAtEnd()) {
        oldLines.add(""); //$NON-NLS-1$
    }

    final StringBuilder sb = new StringBuilder();
    for (final 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);
    setText(sb.toString());
}

From source file:de.codesourcery.gittimelapse.TextFile.java

License:Apache License

public void backwardsPatch(Patch patch) throws IOException, PatchApplyException {
    if (patch.getFiles().size() != 1) {
        throw new IllegalArgumentException("Patch needs to contain exactly one FileHeader");
    }//from  www.j ava  2s .  c  o  m

    final FileHeader fh = patch.getFiles().get(0);

    final List<String> oldLines = new ArrayList<String>(rawText.size());
    for (int i = 0; i < rawText.size(); i++) {
        oldLines.add(rawText.getString(i));
    }
    final List<String> newLines = new ArrayList<String>(oldLines);
    for (final HunkHeader hh : fh.getHunks()) {
        final StringBuilder hunk = new StringBuilder();
        for (int j = hh.getStartOffset(); j < hh.getEndOffset(); j++) {
            hunk.append((char) hh.getBuffer()[j]);
        }
        final RawText hrt = new RawText(hunk.toString().getBytes());
        final List<String> hunkLines = new ArrayList<String>(hrt.size());
        for (int i = 0; i < hrt.size(); i++) {
            hunkLines.add(hrt.getString(i));
        }
        int pos = 0;
        for (int j = 1; j < hunkLines.size(); j++) {
            final String hunkLine = hunkLines.get(j);
            switch (hunkLine.charAt(0)) {
            case ' ':
                if (!newLines.get(hh.getNewStartLine() - 1 + pos).equals(hunkLine.substring(1))) {
                    throw new PatchApplyException(MessageFormat.format(JGitText.get().patchApplyException, hh));
                }
                pos++;
                break;
            case '-':
                if (!newLines.get(hh.getNewStartLine() - 1 + pos).equals(hunkLine.substring(1))) {
                    throw new PatchApplyException(MessageFormat.format(JGitText.get().patchApplyException, hh));
                }
                newLines.remove(hh.getNewStartLine() - 1 + pos);
                break;
            case '+':
                newLines.add(hh.getNewStartLine() - 1 + pos, hunkLine.substring(1));
                changesByLine.put(hh.getNewStartLine() - 1 + pos, ChangeType.ADDED);
                pos++;
                break;
            }
        }
    }
    if (!isNoNewlineAtEndOfFile(fh)) {
        newLines.add(""); //$NON-NLS-1$
    }

    if (!rawText.isMissingNewlineAtEnd()) {
        oldLines.add(""); //$NON-NLS-1$
    }

    final StringBuilder sb = new StringBuilder();
    for (final 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);
    setText(sb.toString());
}