You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DiffFormatter.java 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2008-2009, Johannes E. Schindelin <johannes.schindelin@gmx.de>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.diff;
  45. import static org.eclipse.jgit.lib.Constants.encodeASCII;
  46. import java.io.IOException;
  47. import java.io.OutputStream;
  48. import java.util.List;
  49. import org.eclipse.jgit.patch.FileHeader;
  50. /**
  51. * Format an {@link EditList} as a Git style unified patch script.
  52. */
  53. public class DiffFormatter {
  54. private static final byte[] noNewLine = encodeASCII("\\ No newline at end of file\n");
  55. private int context;
  56. /** Create a new formatter with a default level of context. */
  57. public DiffFormatter() {
  58. setContext(3);
  59. }
  60. /**
  61. * Change the number of lines of context to display.
  62. *
  63. * @param lineCount
  64. * number of lines of context to see before the first
  65. * modification and after the last modification within a hunk of
  66. * the modified file.
  67. */
  68. public void setContext(final int lineCount) {
  69. if (lineCount < 0)
  70. throw new IllegalArgumentException("context must be >= 0");
  71. context = lineCount;
  72. }
  73. /**
  74. * Format a patch script, reusing a previously parsed FileHeader.
  75. * <p>
  76. * This formatter is primarily useful for editing an existing patch script
  77. * to increase or reduce the number of lines of context within the script.
  78. * All header lines are reused as-is from the supplied FileHeader.
  79. *
  80. * @param out
  81. * stream to write the patch script out to.
  82. * @param head
  83. * existing file header containing the header lines to copy.
  84. * @param a
  85. * text source for the pre-image version of the content. This
  86. * must match the content of {@link FileHeader#getOldId()}.
  87. * @param b
  88. * text source for the post-image version of the content. This
  89. * must match the content of {@link FileHeader#getNewId()}.
  90. * @throws IOException
  91. * writing to the supplied stream failed.
  92. */
  93. public void format(final OutputStream out, final FileHeader head,
  94. final RawText a, final RawText b) throws IOException {
  95. // Reuse the existing FileHeader as-is by blindly copying its
  96. // header lines, but avoiding its hunks. Instead we recreate
  97. // the hunks from the text instances we have been supplied.
  98. //
  99. final int start = head.getStartOffset();
  100. int end = head.getEndOffset();
  101. if (!head.getHunks().isEmpty())
  102. end = head.getHunks().get(0).getStartOffset();
  103. out.write(head.getBuffer(), start, end - start);
  104. formatEdits(out, a, b, head.toEditList());
  105. }
  106. /**
  107. * Formats a list of edits in unified diff format
  108. * @param out where the unified diff is written to
  109. * @param a the text A which was compared
  110. * @param b the text B which was compared
  111. * @param edits some differences which have been calculated between A and B
  112. * @throws IOException
  113. */
  114. public void formatEdits(final OutputStream out, final RawText a,
  115. final RawText b, final EditList edits) throws IOException {
  116. for (int curIdx = 0; curIdx < edits.size();) {
  117. Edit curEdit = edits.get(curIdx);
  118. final int endIdx = findCombinedEnd(edits, curIdx);
  119. final Edit endEdit = edits.get(endIdx);
  120. int aCur = Math.max(0, curEdit.getBeginA() - context);
  121. int bCur = Math.max(0, curEdit.getBeginB() - context);
  122. final int aEnd = Math.min(a.size(), endEdit.getEndA() + context);
  123. final int bEnd = Math.min(b.size(), endEdit.getEndB() + context);
  124. writeHunkHeader(out, aCur, aEnd, bCur, bEnd);
  125. while (aCur < aEnd || bCur < bEnd) {
  126. if (aCur < curEdit.getBeginA() || endIdx + 1 < curIdx) {
  127. writeLine(out, ' ', a, aCur);
  128. aCur++;
  129. bCur++;
  130. } else if (aCur < curEdit.getEndA()) {
  131. writeLine(out, '-', a, aCur++);
  132. } else if (bCur < curEdit.getEndB()) {
  133. writeLine(out, '+', b, bCur++);
  134. }
  135. if (end(curEdit, aCur, bCur) && ++curIdx < edits.size())
  136. curEdit = edits.get(curIdx);
  137. }
  138. }
  139. }
  140. private void writeHunkHeader(final OutputStream out, int aCur, int aEnd,
  141. int bCur, int bEnd) throws IOException {
  142. out.write('@');
  143. out.write('@');
  144. writeRange(out, '-', aCur + 1, aEnd - aCur);
  145. writeRange(out, '+', bCur + 1, bEnd - bCur);
  146. out.write(' ');
  147. out.write('@');
  148. out.write('@');
  149. out.write('\n');
  150. }
  151. private static void writeRange(final OutputStream out, final char prefix,
  152. final int begin, final int cnt) throws IOException {
  153. out.write(' ');
  154. out.write(prefix);
  155. switch (cnt) {
  156. case 0:
  157. // If the range is empty, its beginning number must be the
  158. // line just before the range, or 0 if the range is at the
  159. // start of the file stream. Here, begin is always 1 based,
  160. // so an empty file would produce "0,0".
  161. //
  162. out.write(encodeASCII(begin - 1));
  163. out.write(',');
  164. out.write('0');
  165. break;
  166. case 1:
  167. // If the range is exactly one line, produce only the number.
  168. //
  169. out.write(encodeASCII(begin));
  170. break;
  171. default:
  172. out.write(encodeASCII(begin));
  173. out.write(',');
  174. out.write(encodeASCII(cnt));
  175. break;
  176. }
  177. }
  178. private static void writeLine(final OutputStream out, final char prefix,
  179. final RawText text, final int cur) throws IOException {
  180. out.write(prefix);
  181. text.writeLine(out, cur);
  182. out.write('\n');
  183. if (cur + 1 == text.size() && text.isMissingNewlineAtEnd())
  184. out.write(noNewLine);
  185. }
  186. private int findCombinedEnd(final List<Edit> edits, final int i) {
  187. int end = i + 1;
  188. while (end < edits.size()
  189. && (combineA(edits, end) || combineB(edits, end)))
  190. end++;
  191. return end - 1;
  192. }
  193. private boolean combineA(final List<Edit> e, final int i) {
  194. return e.get(i).getBeginA() - e.get(i - 1).getEndA() <= 2 * context;
  195. }
  196. private boolean combineB(final List<Edit> e, final int i) {
  197. return e.get(i).getBeginB() - e.get(i - 1).getEndB() <= 2 * context;
  198. }
  199. private static boolean end(final Edit edit, final int a, final int b) {
  200. return edit.getEndA() <= a && edit.getEndB() <= b;
  201. }
  202. }