Beispiel #1
0
  /**
   * Formats a list of edits in unified diff format
   *
   * @param edits some differences which have been calculated between A and B
   * @param a the text A which was compared
   * @param b the text B which was compared
   * @throws IOException
   */
  public void format(final EditList edits, final RawText a, final RawText b) throws IOException {
    for (int curIdx = 0; curIdx < edits.size(); ) {
      Edit curEdit = edits.get(curIdx);
      final int endIdx = findCombinedEnd(edits, curIdx);
      final Edit endEdit = edits.get(endIdx);

      int aCur = Math.max(0, curEdit.getBeginA() - context);
      int bCur = Math.max(0, curEdit.getBeginB() - context);
      final int aEnd = Math.min(a.size(), endEdit.getEndA() + context);
      final int bEnd = Math.min(b.size(), endEdit.getEndB() + context);

      writeHunkHeader(aCur, aEnd, bCur, bEnd);

      while (aCur < aEnd || bCur < bEnd) {
        if (aCur < curEdit.getBeginA() || endIdx + 1 < curIdx) {
          writeContextLine(a, aCur);
          if (isEndOfLineMissing(a, aCur)) out.write(noNewLine);
          aCur++;
          bCur++;
        } else if (aCur < curEdit.getEndA()) {
          writeRemovedLine(a, aCur);
          if (isEndOfLineMissing(a, aCur)) out.write(noNewLine);
          aCur++;
        } else if (bCur < curEdit.getEndB()) {
          writeAddedLine(b, bCur);
          if (isEndOfLineMissing(b, bCur)) out.write(noNewLine);
          bCur++;
        }

        if (end(curEdit, aCur, bCur) && ++curIdx < edits.size()) curEdit = edits.get(curIdx);
      }
    }
  }
Beispiel #2
0
  private FormatResult createFormatResult(DiffEntry ent)
      throws IOException, CorruptObjectException, MissingObjectException {
    final FormatResult res = new FormatResult();
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final EditList editList;
    final FileHeader.PatchType type;

    formatHeader(buf, ent);

    if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) {
      formatOldNewPaths(buf, ent);
      writeGitLinkDiffText(buf, ent);
      editList = new EditList();
      type = PatchType.UNIFIED;

    } else {
      assertHaveRepository();

      byte[] aRaw = open(OLD, ent);
      byte[] bRaw = open(NEW, ent);

      if (aRaw == BINARY
          || bRaw == BINARY //
          || RawText.isBinary(aRaw)
          || RawText.isBinary(bRaw)) {
        formatOldNewPaths(buf, ent);
        buf.write(encodeASCII("Binary files differ\n")); // $NON-NLS-1$
        editList = new EditList();
        type = PatchType.BINARY;

      } else {
        res.a = new RawText(aRaw);
        res.b = new RawText(bRaw);
        editList = diff(res.a, res.b);
        type = PatchType.UNIFIED;

        switch (ent.getChangeType()) {
          case RENAME:
          case COPY:
            if (!editList.isEmpty()) formatOldNewPaths(buf, ent);
            break;

          default:
            formatOldNewPaths(buf, ent);
            break;
        }
      }
    }

    res.header = new FileHeader(buf.toByteArray(), editList, type);
    return res;
  }
  public void testEqualsWithoutWhitespace() {
    final RawText a = new RawText(cmp, Constants.encodeASCII("foo-a\nfoo-b\nfoo\n"));
    final RawText b = new RawText(cmp, Constants.encodeASCII("foo-b\nfoo-c\nf\n"));

    assertEquals(3, a.size());
    assertEquals(3, b.size());

    // foo-a != foo-b
    assertFalse(cmp.equals(a, 0, b, 0));
    assertFalse(cmp.equals(b, 0, a, 0));

    // foo-b == foo-b
    assertTrue(cmp.equals(a, 1, b, 0));
    assertTrue(cmp.equals(b, 0, a, 1));

    // foo != f
    assertFalse(cmp.equals(a, 2, b, 2));
    assertFalse(cmp.equals(b, 2, a, 2));
  }
  protected void process(HttpServletRequest hreq, HttpServletResponse hresp)
      throws ServletException, IOException {
    Request req = createRequest(hreq, hresp);
    if (L.isDebugEnabled()) L.debug(null, req.toString());

    Response resp = createResponse(hreq, hresp);
    try {
      fireBeforeAll(req, resp);
      if (routeSummary
          && "$"
              .equals(StringUtils.removeStart(StringUtils.trimToEmpty(hreq.getPathInfo()), "/"))) {
        resp.body(RawText.of(makeRouteSummary()));
        resp.type("text/plain");
      } else {
        invokeAllMatched(before, req, resp);
        boolean matched = invokeFirstMatched(routes, req, resp);
        invokeAllMatched(after, req, resp);
        if (!matched) TopazHelper.halt(404, "Route error");

        if (L.isDebugEnabled()) L.debug(null, "ok");
      }
      fireSuccess(req, resp);
    } catch (Throwable t) {
      fireExceptionCaught(req, resp, t);
      Throwable c =
          (t instanceof InvocationTargetException)
              ? ((InvocationTargetException) t).getTargetException()
              : t;
      if (!(c instanceof QuietHaltException)) resp.error(c);

      L.warn(null, c, "error");
    } finally {
      fireBeforeOutput(req, resp);
      resp.doOutput(Response.OutputOptions.fromRequest(req));
      fireAfterOutput(req, resp);
      req.deleteUploadedFiles();
      fireAfterAll(req, resp);
      if (L.isDebugEnabled()) L.debug(null, "complete");
    }
  }
  @Nullable
  private static String getStringContent(@Nullable Producer<Transferable> producer) {
    Transferable content = null;
    if (producer != null) {
      content = producer.produce();
    } else {
      CopyPasteManager manager = CopyPasteManager.getInstance();
      if (manager.areDataFlavorsAvailable(DataFlavor.stringFlavor)) {
        content = manager.getContents();
      }
    }
    if (content == null) return null;

    RawText raw = RawText.fromTransferable(content);
    if (raw != null) return raw.rawText;

    try {
      return (String) content.getTransferData(DataFlavor.stringFlavor);
    } catch (UnsupportedFlavorException ignore) {
    } catch (IOException ignore) {
    }

    return null;
  }
Beispiel #6
0
 /**
  * Write a standard patch script line.
  *
  * @param prefix prefix before the line, typically '-', '+', ' '.
  * @param text the text object to obtain the line from.
  * @param cur line number to output.
  * @throws IOException the stream threw an exception while writing to it.
  */
 protected void writeLine(final char prefix, final RawText text, final int cur)
     throws IOException {
   out.write(prefix);
   text.writeLine(out, cur);
   out.write('\n');
 }
Beispiel #7
0
 private boolean isEndOfLineMissing(final RawText text, final int line) {
   return line + 1 == text.size() && text.isMissingNewlineAtEnd();
 }
Beispiel #8
0
  private static void doPaste(
      final Editor editor,
      final Project project,
      final PsiFile file,
      final Document document,
      final Producer<Transferable> producer) {
    Transferable content = null;

    if (producer != null) {
      content = producer.produce();
    } else {
      CopyPasteManager manager = CopyPasteManager.getInstance();
      if (manager.areDataFlavorsAvailable(DataFlavor.stringFlavor)) {
        content = manager.getContents();
        if (content != null) {
          manager.stopKillRings();
        }
      }
    }

    if (content != null) {
      String text = null;
      try {
        text = (String) content.getTransferData(DataFlavor.stringFlavor);
      } catch (Exception e) {
        editor.getComponent().getToolkit().beep();
      }
      if (text == null) return;

      final CodeInsightSettings settings = CodeInsightSettings.getInstance();

      final Map<CopyPastePostProcessor, TextBlockTransferableData> extraData =
          new HashMap<CopyPastePostProcessor, TextBlockTransferableData>();
      for (CopyPastePostProcessor processor :
          Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
        TextBlockTransferableData data = processor.extractTransferableData(content);
        if (data != null) {
          extraData.put(processor, data);
        }
      }

      text = TextBlockTransferable.convertLineSeparators(text, "\n", extraData.values());

      final CaretModel caretModel = editor.getCaretModel();
      final SelectionModel selectionModel = editor.getSelectionModel();
      final int col = caretModel.getLogicalPosition().column;

      // There is a possible case that we want to perform paste while there is an active selection
      // at the editor and caret is located
      // inside it (e.g. Ctrl+A is pressed while caret is not at the zero column). We want to insert
      // the text at selection start column
      // then, hence, inserted block of text should be indented according to the selection start as
      // well.
      final int blockIndentAnchorColumn;
      final int caretOffset = caretModel.getOffset();
      if (selectionModel.hasSelection() && caretOffset >= selectionModel.getSelectionStart()) {
        blockIndentAnchorColumn =
            editor.offsetToLogicalPosition(selectionModel.getSelectionStart()).column;
      } else {
        blockIndentAnchorColumn = col;
      }

      // We assume that EditorModificationUtil.insertStringAtCaret() is smart enough to remove
      // currently selected text (if any).

      RawText rawText = RawText.fromTransferable(content);
      String newText = text;
      for (CopyPastePreProcessor preProcessor :
          Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
        newText = preProcessor.preprocessOnPaste(project, file, editor, newText, rawText);
      }
      int indentOptions =
          text.equals(newText) ? settings.REFORMAT_ON_PASTE : CodeInsightSettings.REFORMAT_BLOCK;
      text = newText;

      if (LanguageFormatting.INSTANCE.forContext(file) == null
          && indentOptions != CodeInsightSettings.NO_REFORMAT) {
        indentOptions = CodeInsightSettings.INDENT_BLOCK;
      }

      final String _text = text;
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  EditorModificationUtil.insertStringAtCaret(editor, _text, false, true);
                }
              });

      int length = text.length();
      int offset = caretModel.getOffset() - length;
      if (offset < 0) {
        length += offset;
        offset = 0;
      }
      final RangeMarker bounds = document.createRangeMarker(offset, offset + length);

      caretModel.moveToOffset(bounds.getEndOffset());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      selectionModel.removeSelection();

      final Ref<Boolean> indented = new Ref<Boolean>(Boolean.FALSE);
      for (Map.Entry<CopyPastePostProcessor, TextBlockTransferableData> e : extraData.entrySet()) {
        //noinspection unchecked
        e.getKey()
            .processTransferableData(project, editor, bounds, caretOffset, indented, e.getValue());
      }

      boolean pastedTextContainsWhiteSpacesOnly =
          CharArrayUtil.shiftForward(document.getCharsSequence(), bounds.getStartOffset(), " \n\t")
              >= bounds.getEndOffset();

      VirtualFile virtualFile = file.getVirtualFile();
      if (!pastedTextContainsWhiteSpacesOnly
          && (virtualFile == null
              || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) {
        final int indentOptions1 = indentOptions;
        ApplicationManager.getApplication()
            .runWriteAction(
                new Runnable() {
                  @Override
                  public void run() {
                    switch (indentOptions1) {
                      case CodeInsightSettings.INDENT_BLOCK:
                        if (!indented.get()) {
                          indentBlock(
                              project,
                              editor,
                              bounds.getStartOffset(),
                              bounds.getEndOffset(),
                              blockIndentAnchorColumn);
                        }
                        break;

                      case CodeInsightSettings.INDENT_EACH_LINE:
                        if (!indented.get()) {
                          indentEachLine(
                              project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        }
                        break;

                      case CodeInsightSettings.REFORMAT_BLOCK:
                        indentEachLine(
                            project,
                            editor,
                            bounds.getStartOffset(),
                            bounds
                                .getEndOffset()); // this is needed for example when inserting a
                                                  // comment before method
                        reformatBlock(
                            project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        break;
                    }
                  }
                });
      }

      if (bounds.isValid()) {
        caretModel.moveToOffset(bounds.getEndOffset());
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        selectionModel.removeSelection();
        editor.putUserData(EditorEx.LAST_PASTED_REGION, TextRange.create(bounds));
      }
    }
  }