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.

RawText.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 java.io.EOFException;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.OutputStream;
  50. import org.eclipse.jgit.errors.BinaryBlobException;
  51. import org.eclipse.jgit.errors.LargeObjectException;
  52. import org.eclipse.jgit.lib.ObjectLoader;
  53. import org.eclipse.jgit.util.IO;
  54. import org.eclipse.jgit.util.IntList;
  55. import org.eclipse.jgit.util.RawParseUtils;
  56. /**
  57. * A Sequence supporting UNIX formatted text in byte[] format.
  58. * <p>
  59. * Elements of the sequence are the lines of the file, as delimited by the UNIX
  60. * newline character ('\n'). The file content is treated as 8 bit binary text,
  61. * with no assumptions or requirements on character encoding.
  62. * <p>
  63. * Note that the first line of the file is element 0, as defined by the Sequence
  64. * interface API. Traditionally in a text editor a patch file the first line is
  65. * line number 1. Callers may need to subtract 1 prior to invoking methods if
  66. * they are converting from "line number" to "element index".
  67. */
  68. public class RawText extends Sequence {
  69. /** A RawText of length 0 */
  70. public static final RawText EMPTY_TEXT = new RawText(new byte[0]);
  71. /** Number of bytes to check for heuristics in {@link #isBinary(byte[])} */
  72. private static final int FIRST_FEW_BYTES = 8000;
  73. /** The file content for this sequence. */
  74. protected final byte[] content;
  75. /** Map of line number to starting position within {@link #content}. */
  76. protected final IntList lines;
  77. /**
  78. * Create a new sequence from an existing content byte array.
  79. * <p>
  80. * The entire array (indexes 0 through length-1) is used as the content.
  81. *
  82. * @param input
  83. * the content array. The array is never modified, so passing
  84. * through cached arrays is safe.
  85. */
  86. public RawText(final byte[] input) {
  87. content = input;
  88. lines = RawParseUtils.lineMap(content, 0, content.length);
  89. }
  90. /**
  91. * Create a new sequence from a file.
  92. * <p>
  93. * The entire file contents are used.
  94. *
  95. * @param file
  96. * the text file.
  97. * @throws IOException
  98. * if Exceptions occur while reading the file
  99. */
  100. public RawText(File file) throws IOException {
  101. this(IO.readFully(file));
  102. }
  103. /** @return total number of items in the sequence. */
  104. @Override
  105. public int size() {
  106. // The line map is always 2 entries larger than the number of lines in
  107. // the file. Index 0 is padded out/unused. The last index is the total
  108. // length of the buffer, and acts as a sentinel.
  109. //
  110. return lines.size() - 2;
  111. }
  112. /**
  113. * Write a specific line to the output stream, without its trailing LF.
  114. * <p>
  115. * The specified line is copied as-is, with no character encoding
  116. * translation performed.
  117. * <p>
  118. * If the specified line ends with an LF ('\n'), the LF is <b>not</b>
  119. * copied. It is up to the caller to write the LF, if desired, between
  120. * output lines.
  121. *
  122. * @param out
  123. * stream to copy the line data onto.
  124. * @param i
  125. * index of the line to extract. Note this is 0-based, so line
  126. * number 1 is actually index 0.
  127. * @throws IOException
  128. * the stream write operation failed.
  129. */
  130. public void writeLine(final OutputStream out, final int i)
  131. throws IOException {
  132. int start = getStart(i);
  133. int end = getEnd(i);
  134. if (content[end - 1] == '\n')
  135. end--;
  136. out.write(content, start, end - start);
  137. }
  138. /**
  139. * Determine if the file ends with a LF ('\n').
  140. *
  141. * @return true if the last line has an LF; false otherwise.
  142. */
  143. public boolean isMissingNewlineAtEnd() {
  144. final int end = lines.get(lines.size() - 1);
  145. if (end == 0)
  146. return true;
  147. return content[end - 1] != '\n';
  148. }
  149. /**
  150. * Get the text for a single line.
  151. *
  152. * @param i
  153. * index of the line to extract. Note this is 0-based, so line
  154. * number 1 is actually index 0.
  155. * @return the text for the line, without a trailing LF.
  156. */
  157. public String getString(int i) {
  158. return getString(i, i + 1, true);
  159. }
  160. /**
  161. * Get the text for a region of lines.
  162. *
  163. * @param begin
  164. * index of the first line to extract. Note this is 0-based, so
  165. * line number 1 is actually index 0.
  166. * @param end
  167. * index of one past the last line to extract.
  168. * @param dropLF
  169. * if true the trailing LF ('\n') of the last returned line is
  170. * dropped, if present.
  171. * @return the text for lines {@code [begin, end)}.
  172. */
  173. public String getString(int begin, int end, boolean dropLF) {
  174. if (begin == end)
  175. return ""; //$NON-NLS-1$
  176. int s = getStart(begin);
  177. int e = getEnd(end - 1);
  178. if (dropLF && content[e - 1] == '\n')
  179. e--;
  180. return decode(s, e);
  181. }
  182. /**
  183. * Decode a region of the text into a String.
  184. *
  185. * The default implementation of this method tries to guess the character
  186. * set by considering UTF-8, the platform default, and falling back on
  187. * ISO-8859-1 if neither of those can correctly decode the region given.
  188. *
  189. * @param start
  190. * first byte of the content to decode.
  191. * @param end
  192. * one past the last byte of the content to decode.
  193. * @return the region {@code [start, end)} decoded as a String.
  194. */
  195. protected String decode(int start, int end) {
  196. return RawParseUtils.decode(content, start, end);
  197. }
  198. private int getStart(final int i) {
  199. return lines.get(i + 1);
  200. }
  201. private int getEnd(final int i) {
  202. return lines.get(i + 2);
  203. }
  204. /**
  205. * Determine heuristically whether a byte array represents binary (as
  206. * opposed to text) content.
  207. *
  208. * @param raw
  209. * the raw file content.
  210. * @return true if raw is likely to be a binary file, false otherwise
  211. */
  212. public static boolean isBinary(byte[] raw) {
  213. return isBinary(raw, raw.length);
  214. }
  215. /**
  216. * Determine heuristically whether the bytes contained in a stream
  217. * represents binary (as opposed to text) content.
  218. *
  219. * Note: Do not further use this stream after having called this method! The
  220. * stream may not be fully read and will be left at an unknown position
  221. * after consuming an unknown number of bytes. The caller is responsible for
  222. * closing the stream.
  223. *
  224. * @param raw
  225. * input stream containing the raw file content.
  226. * @return true if raw is likely to be a binary file, false otherwise
  227. * @throws IOException
  228. * if input stream could not be read
  229. */
  230. public static boolean isBinary(InputStream raw) throws IOException {
  231. final byte[] buffer = new byte[FIRST_FEW_BYTES];
  232. int cnt = 0;
  233. while (cnt < buffer.length) {
  234. final int n = raw.read(buffer, cnt, buffer.length - cnt);
  235. if (n == -1)
  236. break;
  237. cnt += n;
  238. }
  239. return isBinary(buffer, cnt);
  240. }
  241. /**
  242. * Determine heuristically whether a byte array represents binary (as
  243. * opposed to text) content.
  244. *
  245. * @param raw
  246. * the raw file content.
  247. * @param length
  248. * number of bytes in {@code raw} to evaluate. This should be
  249. * {@code raw.length} unless {@code raw} was over-allocated by
  250. * the caller.
  251. * @return true if raw is likely to be a binary file, false otherwise
  252. */
  253. public static boolean isBinary(byte[] raw, int length) {
  254. // Same heuristic as C Git
  255. if (length > FIRST_FEW_BYTES)
  256. length = FIRST_FEW_BYTES;
  257. for (int ptr = 0; ptr < length; ptr++)
  258. if (raw[ptr] == '\0')
  259. return true;
  260. return false;
  261. }
  262. /**
  263. * Get the line delimiter for the first line.
  264. *
  265. * @since 2.0
  266. * @return the line delimiter or <code>null</code>
  267. */
  268. public String getLineDelimiter() {
  269. if (size() == 0)
  270. return null;
  271. int e = getEnd(0);
  272. if (content[e - 1] != '\n')
  273. return null;
  274. if (content.length > 1 && e > 1 && content[e - 2] == '\r')
  275. return "\r\n"; //$NON-NLS-1$
  276. else
  277. return "\n"; //$NON-NLS-1$
  278. }
  279. /**
  280. * Read a blob object into RawText, or throw BinaryBlobException if
  281. * the blob is binary.
  282. *
  283. * @param ldr
  284. * the ObjectLoader for the blob
  285. * @param threshold
  286. * if the blob is larger than this size, it is always assumed to be binary.
  287. * @since 4.10
  288. * @return the RawText representing the blob.
  289. * @throws BinaryBlobException if the blob contains binary data.
  290. * @throws IOException if the input could not be read.
  291. */
  292. public static RawText load(ObjectLoader ldr, int threshold) throws IOException, BinaryBlobException {
  293. long sz = ldr.getSize();
  294. if (sz > threshold) {
  295. throw new BinaryBlobException();
  296. }
  297. if (sz <= FIRST_FEW_BYTES) {
  298. byte[] data = ldr.getCachedBytes(FIRST_FEW_BYTES);
  299. if (isBinary(data)) {
  300. throw new BinaryBlobException();
  301. }
  302. return new RawText(data);
  303. }
  304. byte[] head = new byte[FIRST_FEW_BYTES];
  305. try (InputStream stream = ldr.openStream()) {
  306. int off = 0;
  307. int left = head.length;
  308. while (left > 0) {
  309. int n = stream.read(head, off, left);
  310. if (n < 0) {
  311. throw new EOFException();
  312. }
  313. left -= n;
  314. while (n > 0) {
  315. if (head[off] == '\0') {
  316. throw new BinaryBlobException();
  317. }
  318. off++;
  319. n--;
  320. }
  321. }
  322. byte data[];
  323. try {
  324. data = new byte[(int)sz];
  325. } catch (OutOfMemoryError e) {
  326. throw new LargeObjectException.OutOfMemory(e);
  327. }
  328. System.arraycopy(head, 0, data, 0, head.length);
  329. IO.readFully(stream, data, off, (int) (sz-off));
  330. return new RawText(data);
  331. }
  332. }
  333. }