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

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

Introduction

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

Prototype

@Override
public int size() 

Source Link

Usage

From source file:MySmartApply.java

License:Eclipse Distribution License

/**
 * @param f/*w  ww .j  a v  a2 s  .  c om*/
 * @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) {

    // ... ////from   w  w  w .ja va2 s .c o  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();/*from   w  ww .j ava  2s . c o  m*/
    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   w  w  w.  j ava  2 s.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.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

private MergeResult<RawText> contentMerge(CanonicalTreeParser base, CanonicalTreeParser ours,
        CanonicalTreeParser theirs) throws IOException {
    InputStream localIn = getInputStream(ours.getEntryObjectId());
    InputStream remoteIn = getInputStream(theirs.getEntryObjectId());
    InputStream baseIn = getInputStream(base.getEntryObjectId());
    ByteArrayOutputStream resultOut = new ByteArrayOutputStream();

    this.mergeClient.merge(localIn, remoteIn, baseIn, resultOut);
    RawText resultText = new RawText(resultOut.toByteArray());

    List<RawText> sequences = new ArrayList<RawText>(1);
    sequences.add(resultText);/*from   ww  w. j  av  a  2  s.  c om*/
    MergeResult<RawText> result = new MergeResult<RawText>(sequences);
    result.add(0, 0, resultText.size(), ConflictState.NO_CONFLICT);

    return result;
}

From source file:com.madgag.agit.diff.LineContextDiffer.java

License:Open Source License

public List<Hunk> formatEdits(final RawText a, final RawText b, final EditList edits) throws IOException {
    List<Hunk> hunks = newArrayList();
    for (int curIdx = 0; curIdx < edits.size();) {
        Edit curEdit = edits.get(curIdx);
        final int endIdx = findCombinedEnd(edits, curIdx);

        // Log.i("BUCK", "Will do edits "+curIdx+" - "+endIdx);
        final Edit endEdit = edits.get(endIdx);

        int aCur = max(0, curEdit.getBeginA() - context);
        int bCur = max(0, curEdit.getBeginB() - context);
        final int aEnd = min(a.size(), endEdit.getEndA() + context);
        final int bEnd = min(b.size(), endEdit.getEndB() + context);
        String before = extractHunk(a, aCur, aEnd), after = extractHunk(b, bCur, bEnd);
        hunks.add(new Hunk(before, after));
        curIdx = endIdx + 1;/*w w w  .  j a  v  a 2s .  com*/
    }
    return hunks;
}

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);/* www . ja  v a 2  s . com*/
    }

    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: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  a  v  a2  s  . 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

private static boolean isNoNewlineAtEndOfFile(FileHeader fh) {
    final HunkHeader lastHunk = fh.getHunks().get(fh.getHunks().size() - 1);
    final 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:de.codesourcery.gittimelapse.TextFile.java

License:Apache License

public static String toString(RawText rt) {
    return rt.getString(0, rt.size(), false);
}