Example usage for org.eclipse.jgit.diff RawText getString

List of usage examples for org.eclipse.jgit.diff RawText getString

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff RawText getString.

Prototype

public String getString(int i) 

Source Link

Document

Get the text for a single line.

Usage

From source file:MySmartApply.java

License:Eclipse Distribution License

/**
 * @param f/*from   w w  w .j av 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) {

    // ... ////  w w  w. ja va2 s .co m

    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.chungkwong.jgitgui.StageTreeItem.java

License:Open Source License

@Override
public Node getContentPage() {
    Git git = (Git) getValue();//ww  w . ja v a  2s .com
    GridPane page = new GridPane();
    ListView<String> list = new ListView<String>();
    GridPane.setHgrow(list, Priority.ALWAYS);
    GridPane.setVgrow(list, Priority.ALWAYS);
    list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    try {
        DirCache cache = ((Git) getValue()).getRepository().readDirCache();
        for (int i = 0; i < cache.getEntryCount(); i++)
            list.getItems().add(cache.getEntry(i).getPathString());
    } catch (Exception ex) {
        Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
    Button remove = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("REMOVE"));
    remove.setOnAction((e) -> {
        RmCommand command = git.rm().setCached(true);
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            command.addFilepattern(path);
        });
        list.getItems().removeAll(list.getSelectionModel().getSelectedItems());
        try {
            command.call();
        } catch (Exception ex) {
            Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Util.informUser(ex);
        }
    });
    Button blame = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
    blame.setOnAction((e) -> {
        Stage dialog = new Stage();
        dialog.setTitle(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
        StringBuilder buf = new StringBuilder();
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            try {
                BlameResult command = git.blame().setFilePath(path).call();
                RawText contents = command.getResultContents();
                for (int i = 0; i < contents.size(); i++) {
                    buf.append(command.getSourcePath(i)).append(':');
                    buf.append(command.getSourceLine(i)).append(':');
                    buf.append(command.getSourceCommit(i)).append(':');
                    buf.append(command.getSourceAuthor(i)).append(':');
                    buf.append(contents.getString(i)).append('\n');
                }
            } catch (Exception ex) {
                Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                Util.informUser(ex);
            }
        });
        dialog.setScene(new Scene(new TextArea(buf.toString())));
        dialog.setMaximized(true);
        dialog.show();
    });
    page.addColumn(0, list, remove, blame);
    return page;
}

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

License:Apache License

/**
 * Returns the list of lines in the specified source file annotated with the
 * source commit metadata.//from   www  .j a va2s.c  o  m
 *
 * @param repository
 * @param blobPath
 * @param objectId
 * @return list of annotated lines
 */
public static List<AnnotatedLine> blame(Repository repository, String blobPath, String objectId) {
    List<AnnotatedLine> lines = new ArrayList<AnnotatedLine>();
    try {
        ObjectId object;
        if (StringUtils.isEmpty(objectId)) {
            object = JGitUtils.getDefaultBranch(repository);
        } else {
            object = repository.resolve(objectId);
        }
        BlameCommand blameCommand = new BlameCommand(repository);
        blameCommand.setFilePath(blobPath);
        blameCommand.setStartCommit(object);
        BlameResult blameResult = blameCommand.call();
        RawText rawText = blameResult.getResultContents();
        int length = rawText.size();
        for (int i = 0; i < length; i++) {
            RevCommit commit = blameResult.getSourceCommit(i);
            AnnotatedLine line = new AnnotatedLine(commit, i + 1, rawText.getString(i));
            lines.add(line);
        }
    } catch (Throwable t) {
        LOGGER.error(MessageFormat.format("failed to generate blame for {0} {1}!", blobPath, objectId), t);
    }
    return lines;
}

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

License:Apache License

@Override
protected void writeLine(final char prefix, final RawText text, final int cur) throws IOException {
    if (nofLinesCurrent++ == 0) {
        handleChange();//from   ww w. j av a 2s .c o  m
        startCurrent = os.size();
    }
    // update entry diffstat
    currentPath.update(prefix);
    if (isOff) {
        return;
    }
    totalNofLinesCurrent++;
    if (nofLinesCurrent > maxDiffLinesPerFile && maxDiffLinesPerFile > 0) {
        reset();
    } else {
        // output diff
        os.write("<tr>".getBytes());
        switch (prefix) {
        case '+':
            os.write(("<th class='diff-line'></th><th class='diff-line' data-lineno='" + (right++) + "'></th>")
                    .getBytes());
            os.write("<th class='diff-state diff-state-add'></th>".getBytes());
            os.write("<td class='diff-cell add2'>".getBytes());
            break;
        case '-':
            os.write(("<th class='diff-line' data-lineno='" + (left++) + "'></th><th class='diff-line'></th>")
                    .getBytes());
            os.write("<th class='diff-state diff-state-sub'></th>".getBytes());
            os.write("<td class='diff-cell remove2'>".getBytes());
            break;
        default:
            os.write(("<th class='diff-line' data-lineno='" + (left++)
                    + "'></th><th class='diff-line' data-lineno='" + (right++) + "'></th>").getBytes());
            os.write("<th class='diff-state'></th>".getBytes());
            os.write("<td class='diff-cell context2'>".getBytes());
            break;
        }
        os.write(encode(codeLineToHtml(prefix, text.getString(cur))));
        os.write("</td></tr>\n".getBytes());
    }
}

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

License:Apache License

@Override
protected void writeLine(final char prefix, final RawText text, final int cur) throws IOException {
    switch (prefix) {
    case '+':
        os.write("<span style=\"color:#008000;\">".getBytes());
        break;/*w  w w  .ja v a  2s .c  om*/
    case '-':
        os.write("<span style=\"color:#800000;\">".getBytes());
        break;
    }
    os.write(prefix);
    String line = text.getString(cur);
    line = StringUtils.escapeForHtml(line, false);
    os.write(encode(line));
    switch (prefix) {
    case '+':
    case '-':
        os.write("</span>\n".getBytes());
        break;
    default:
        os.write('\n');
    }
}

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

License:Open Source License

@Override
protected void writeLine(char prefix, RawText text, int cur) throws IOException {
    // Manually render each line, rather than invoke a Soy template. This method
    // can be called thousands of times in a single request. Avoid unnecessary
    // overheads by formatting as-is.
    OutputStream out = getOutputStream();
    switch (prefix) {
    case '+':
        out.write(LINE_INSERT_BEGIN);//from  w ww .j  a v a 2 s.  c o  m
        break;
    case '-':
        out.write(LINE_DELETE_BEGIN);
        break;
    case ' ':
    default:
        out.write(LINE_CHANGE_BEGIN);
        break;
    }
    out.write(StringEscapeUtils.escapeHtml4(text.getString(cur)).getBytes(Charsets.UTF_8));
    out.write(LINE_END);
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Blob getBlob(Repository r, String revision, String path)
        throws IOException, EntityNotFoundException {

    if (path.startsWith("/")) {
        path = path.substring(1);//from w  w w . jav  a 2 s .c o  m
    }

    String id = resolve(r, r.resolve(revision), path);
    if (id == null) {
        throw new EntityNotFoundException();
    }
    ObjectId objectId = ObjectId.fromString(id);

    ObjectLoader loader = r.getObjectDatabase().open(objectId, Constants.OBJ_BLOB);

    Blob b = new Blob(id);

    if (loader.isLarge()) {
        b.setLarge(true);
        InputStream is = null;
        IOException ioex = null;
        try {
            is = loader.openStream();
            b.setBinary(RawText.isBinary(is));
        } catch (IOException ex) {
            ioex = ex;
        } finally {
            if (is != null) {
                is.close();
            }
            if (ioex != null) {
                throw ioex;
            }
        }

    } else {
        byte[] raw = loader.getBytes();

        boolean binary = RawText.isBinary(raw);

        if (binary) {
            b.setBinary(true);
            b.setLines(Collections.<String>emptyList());
        } else {

            RawText rt = new RawText(raw);
            List<String> lines = new ArrayList<String>(rt.size());

            for (int i = 0; i < rt.size(); i++) {
                lines.add(rt.getString(i));
            }

            b.setLines(lines);
        }
    }

    return b;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Blame getBlame(Repository r, String revision, String path) throws IOException, GitAPIException {

    if (path.startsWith("/")) {
        path = path.substring(1);//from w  w w  .j  av a2s.c  om
    }

    Git git = new Git(r);

    ObjectId revId = r.resolve(revision);

    BlameCommand bc = git.blame();
    bc.setStartCommit(revId);
    bc.setFilePath(path);
    BlameResult br = bc.call();

    Blame blame = new Blame();
    blame.path = path;
    blame.revision = revision;
    blame.commits = new ArrayList<Commit>();
    blame.lines = new ArrayList<Blame.Line>();

    Map<String, Integer> sha2idx = new HashMap<String, Integer>();

    RawText resultContents = br.getResultContents();

    for (int i = 0; i < br.getResultContents().size(); i++) {

        RevCommit sourceCommit = br.getSourceCommit(i); // XXX should it really be the source commit
        String sha = sourceCommit.getName();
        Integer cIdx = sha2idx.get(sha);
        if (cIdx == null) {
            cIdx = blame.commits.size();
            Commit commit = GitDomain.createCommit(sourceCommit);
            blame.commits.add(commit);
            sha2idx.put(sha, cIdx);
        }

        Blame.Line bl = new Blame.Line();
        bl.commit = cIdx;
        bl.text = resultContents.getString(i);
        blame.lines.add(bl);
    }

    return blame;
}

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  ww.j av a  2 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 ' ': // 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());
}