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 14KB

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