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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. IntList map;
  89. try {
  90. map = RawParseUtils.lineMap(content, 0, content.length);
  91. } catch (BinaryBlobException e) {
  92. map = new IntList(3);
  93. map.add(Integer.MIN_VALUE);
  94. map.add(0);
  95. map.add(content.length);
  96. }
  97. lines = map;
  98. }
  99. /**
  100. * Construct a new RawText if the line map is already known.
  101. *
  102. * @param data
  103. * the blob data.
  104. * @param lineMap
  105. * Indices of line starts, with indexed by base-1 linenumber.
  106. */
  107. private RawText(final byte[] data, final IntList lineMap) {
  108. content = data;
  109. lines = lineMap;
  110. }
  111. /**
  112. * Create a new sequence from a file.
  113. * <p>
  114. * The entire file contents are used.
  115. *
  116. * @param file
  117. * the text file.
  118. * @throws IOException
  119. * if Exceptions occur while reading the file
  120. */
  121. public RawText(File file) throws IOException {
  122. this(IO.readFully(file));
  123. }
  124. /** @return total number of items in the sequence. */
  125. @Override
  126. public int size() {
  127. // The line map is always 2 entries larger than the number of lines in
  128. // the file. Index 0 is padded out/unused. The last index is the total
  129. // length of the buffer, and acts as a sentinel.
  130. //
  131. return lines.size() - 2;
  132. }
  133. /**
  134. * Write a specific line to the output stream, without its trailing LF.
  135. * <p>
  136. * The specified line is copied as-is, with no character encoding
  137. * translation performed.
  138. * <p>
  139. * If the specified line ends with an LF ('\n'), the LF is <b>not</b>
  140. * copied. It is up to the caller to write the LF, if desired, between
  141. * output lines.
  142. *
  143. * @param out
  144. * stream to copy the line data onto.
  145. * @param i
  146. * index of the line to extract. Note this is 0-based, so line
  147. * number 1 is actually index 0.
  148. * @throws IOException
  149. * the stream write operation failed.
  150. */
  151. public void writeLine(final OutputStream out, final int i)
  152. throws IOException {
  153. int start = getStart(i);
  154. int end = getEnd(i);
  155. if (content[end - 1] == '\n')
  156. end--;
  157. out.write(content, start, end - start);
  158. }
  159. /**
  160. * Determine if the file ends with a LF ('\n').
  161. *
  162. * @return true if the last line has an LF; false otherwise.
  163. */
  164. public boolean isMissingNewlineAtEnd() {
  165. final int end = lines.get(lines.size() - 1);
  166. if (end == 0)
  167. return true;
  168. return content[end - 1] != '\n';
  169. }
  170. /**
  171. * Get the text for a single line.
  172. *
  173. * @param i
  174. * index of the line to extract. Note this is 0-based, so line
  175. * number 1 is actually index 0.
  176. * @return the text for the line, without a trailing LF.
  177. */
  178. public String getString(int i) {
  179. return getString(i, i + 1, true);
  180. }
  181. /**
  182. * Get the text for a region of lines.
  183. *
  184. * @param begin
  185. * index of the first line to extract. Note this is 0-based, so
  186. * line number 1 is actually index 0.
  187. * @param end
  188. * index of one past the last line to extract.
  189. * @param dropLF
  190. * if true the trailing LF ('\n') of the last returned line is
  191. * dropped, if present.
  192. * @return the text for lines {@code [begin, end)}.
  193. */
  194. public String getString(int begin, int end, boolean dropLF) {
  195. if (begin == end)
  196. return ""; //$NON-NLS-1$
  197. int s = getStart(begin);
  198. int e = getEnd(end - 1);
  199. if (dropLF && content[e - 1] == '\n')
  200. e--;
  201. return decode(s, e);
  202. }
  203. /**
  204. * Decode a region of the text into a String.
  205. *
  206. * The default implementation of this method tries to guess the character
  207. * set by considering UTF-8, the platform default, and falling back on
  208. * ISO-8859-1 if neither of those can correctly decode the region given.
  209. *
  210. * @param start
  211. * first byte of the content to decode.
  212. * @param end
  213. * one past the last byte of the content to decode.
  214. * @return the region {@code [start, end)} decoded as a String.
  215. */
  216. protected String decode(int start, int end) {
  217. return RawParseUtils.decode(content, start, end);
  218. }
  219. private int getStart(final int i) {
  220. return lines.get(i + 1);
  221. }
  222. private int getEnd(final int i) {
  223. return lines.get(i + 2);
  224. }
  225. /**
  226. * Determine heuristically whether a byte array represents binary (as
  227. * opposed to text) content.
  228. *
  229. * @param raw
  230. * the raw file content.
  231. * @return true if raw is likely to be a binary file, false otherwise
  232. */
  233. public static boolean isBinary(byte[] raw) {
  234. return isBinary(raw, raw.length);
  235. }
  236. /**
  237. * Determine heuristically whether the bytes contained in a stream
  238. * represents binary (as opposed to text) content.
  239. *
  240. * Note: Do not further use this stream after having called this method! The
  241. * stream may not be fully read and will be left at an unknown position
  242. * after consuming an unknown number of bytes. The caller is responsible for
  243. * closing the stream.
  244. *
  245. * @param raw
  246. * input stream containing the raw file content.
  247. * @return true if raw is likely to be a binary file, false otherwise
  248. * @throws IOException
  249. * if input stream could not be read
  250. */
  251. public static boolean isBinary(InputStream raw) throws IOException {
  252. final byte[] buffer = new byte[FIRST_FEW_BYTES];
  253. int cnt = 0;
  254. while (cnt < buffer.length) {
  255. final int n = raw.read(buffer, cnt, buffer.length - cnt);
  256. if (n == -1)
  257. break;
  258. cnt += n;
  259. }
  260. return isBinary(buffer, cnt);
  261. }
  262. /**
  263. * Determine heuristically whether a byte array represents binary (as
  264. * opposed to text) content.
  265. *
  266. * @param raw
  267. * the raw file content.
  268. * @param length
  269. * number of bytes in {@code raw} to evaluate. This should be
  270. * {@code raw.length} unless {@code raw} was over-allocated by
  271. * the caller.
  272. * @return true if raw is likely to be a binary file, false otherwise
  273. */
  274. public static boolean isBinary(byte[] raw, int length) {
  275. // Same heuristic as C Git
  276. if (length > FIRST_FEW_BYTES)
  277. length = FIRST_FEW_BYTES;
  278. for (int ptr = 0; ptr < length; ptr++)
  279. if (raw[ptr] == '\0')
  280. return true;
  281. return false;
  282. }
  283. /**
  284. * Get the line delimiter for the first line.
  285. *
  286. * @since 2.0
  287. * @return the line delimiter or <code>null</code>
  288. */
  289. public String getLineDelimiter() {
  290. if (size() == 0)
  291. return null;
  292. int e = getEnd(0);
  293. if (content[e - 1] != '\n')
  294. return null;
  295. if (content.length > 1 && e > 1 && content[e - 2] == '\r')
  296. return "\r\n"; //$NON-NLS-1$
  297. else
  298. return "\n"; //$NON-NLS-1$
  299. }
  300. /**
  301. * Read a blob object into RawText, or throw BinaryBlobException if
  302. * the blob is binary.
  303. *
  304. * @param ldr
  305. * the ObjectLoader for the blob
  306. * @param threshold
  307. * if the blob is larger than this size, it is always assumed to be binary.
  308. * @since 4.10
  309. * @return the RawText representing the blob.
  310. * @throws BinaryBlobException if the blob contains binary data.
  311. * @throws IOException if the input could not be read.
  312. */
  313. public static RawText load(ObjectLoader ldr, int threshold) throws IOException, BinaryBlobException {
  314. long sz = ldr.getSize();
  315. if (sz > threshold) {
  316. throw new BinaryBlobException();
  317. }
  318. if (sz <= FIRST_FEW_BYTES) {
  319. byte[] data = ldr.getCachedBytes(FIRST_FEW_BYTES);
  320. if (isBinary(data)) {
  321. throw new BinaryBlobException();
  322. }
  323. return new RawText(data);
  324. }
  325. byte[] head = new byte[FIRST_FEW_BYTES];
  326. try (InputStream stream = ldr.openStream()) {
  327. int off = 0;
  328. int left = head.length;
  329. while (left > 0) {
  330. int n = stream.read(head, off, left);
  331. if (n < 0) {
  332. throw new EOFException();
  333. }
  334. left -= n;
  335. while (n > 0) {
  336. if (head[off] == '\0') {
  337. throw new BinaryBlobException();
  338. }
  339. off++;
  340. n--;
  341. }
  342. }
  343. byte data[];
  344. try {
  345. data = new byte[(int)sz];
  346. } catch (OutOfMemoryError e) {
  347. throw new LargeObjectException.OutOfMemory(e);
  348. }
  349. System.arraycopy(head, 0, data, 0, head.length);
  350. IO.readFully(stream, data, off, (int) (sz-off));
  351. IntList lineMap = RawParseUtils.lineMap(data, 0, data.length);
  352. return new RawText(data, lineMap);
  353. }
  354. }
  355. }