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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2008-2021, Johannes E. Schindelin <johannes.schindelin@gmx.de> and others
  4. *
  5. * This program and the accompanying materials are made available under the
  6. * terms of the Eclipse Distribution License v. 1.0 which is available at
  7. * https://www.eclipse.org/org/documents/edl-v10.php.
  8. *
  9. * SPDX-License-Identifier: BSD-3-Clause
  10. */
  11. package org.eclipse.jgit.diff;
  12. import java.io.EOFException;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.OutputStream;
  17. import java.nio.ByteBuffer;
  18. import org.eclipse.jgit.errors.BinaryBlobException;
  19. import org.eclipse.jgit.errors.LargeObjectException;
  20. import org.eclipse.jgit.lib.ObjectLoader;
  21. import org.eclipse.jgit.util.IO;
  22. import org.eclipse.jgit.util.IntList;
  23. import org.eclipse.jgit.util.RawParseUtils;
  24. /**
  25. * A Sequence supporting UNIX formatted text in byte[] format.
  26. * <p>
  27. * Elements of the sequence are the lines of the file, as delimited by the UNIX
  28. * newline character ('\n'). The file content is treated as 8 bit binary text,
  29. * with no assumptions or requirements on character encoding.
  30. * <p>
  31. * Note that the first line of the file is element 0, as defined by the Sequence
  32. * interface API. Traditionally in a text editor a patch file the first line is
  33. * line number 1. Callers may need to subtract 1 prior to invoking methods if
  34. * they are converting from "line number" to "element index".
  35. */
  36. public class RawText extends Sequence {
  37. /** A RawText of length 0 */
  38. public static final RawText EMPTY_TEXT = new RawText(new byte[0]);
  39. /** Number of bytes to check for heuristics in {@link #isBinary(byte[])} */
  40. static final int FIRST_FEW_BYTES = 8000;
  41. /** The file content for this sequence. */
  42. protected final byte[] content;
  43. /** Map of line number to starting position within {@link #content}. */
  44. protected final IntList lines;
  45. /**
  46. * Create a new sequence from an existing content byte array.
  47. * <p>
  48. * The entire array (indexes 0 through length-1) is used as the content.
  49. *
  50. * @param input
  51. * the content array. The object retains a reference to this
  52. * array, so it should be immutable.
  53. */
  54. public RawText(byte[] input) {
  55. this(input, RawParseUtils.lineMap(input, 0, input.length));
  56. }
  57. /**
  58. * Create a new sequence from the existing content byte array and the line
  59. * map indicating line boundaries.
  60. *
  61. * @param input
  62. * the content array. The object retains a reference to this
  63. * array, so it should be immutable.
  64. * @param lineMap
  65. * an array with 1-based offsets for the start of each line.
  66. * The first and last entries should be {@link Integer#MIN_VALUE}
  67. * and an offset one past the end of the last line, respectively.
  68. * @since 5.0
  69. */
  70. public RawText(byte[] input, IntList lineMap) {
  71. content = input;
  72. lines = lineMap;
  73. }
  74. /**
  75. * Create a new sequence from a file.
  76. * <p>
  77. * The entire file contents are used.
  78. *
  79. * @param file
  80. * the text file.
  81. * @throws java.io.IOException
  82. * if Exceptions occur while reading the file
  83. */
  84. public RawText(File file) throws IOException {
  85. this(IO.readFully(file));
  86. }
  87. /**
  88. * @return the raw, unprocessed content read.
  89. * @since 4.11
  90. */
  91. public byte[] getRawContent() {
  92. return content;
  93. }
  94. /** @return total number of items in the sequence. */
  95. /** {@inheritDoc} */
  96. @Override
  97. public int size() {
  98. // The line map is always 2 entries larger than the number of lines in
  99. // the file. Index 0 is padded out/unused. The last index is the total
  100. // length of the buffer, and acts as a sentinel.
  101. //
  102. return lines.size() - 2;
  103. }
  104. /**
  105. * Write a specific line to the output stream, without its trailing LF.
  106. * <p>
  107. * The specified line is copied as-is, with no character encoding
  108. * translation performed.
  109. * <p>
  110. * If the specified line ends with an LF ('\n'), the LF is <b>not</b>
  111. * copied. It is up to the caller to write the LF, if desired, between
  112. * output lines.
  113. *
  114. * @param out
  115. * stream to copy the line data onto.
  116. * @param i
  117. * index of the line to extract. Note this is 0-based, so line
  118. * number 1 is actually index 0.
  119. * @throws java.io.IOException
  120. * the stream write operation failed.
  121. */
  122. public void writeLine(OutputStream out, int i)
  123. throws IOException {
  124. int start = getStart(i);
  125. int end = getEnd(i);
  126. if (content[end - 1] == '\n')
  127. end--;
  128. out.write(content, start, end - start);
  129. }
  130. /**
  131. * Determine if the file ends with a LF ('\n').
  132. *
  133. * @return true if the last line has an LF; false otherwise.
  134. */
  135. public boolean isMissingNewlineAtEnd() {
  136. final int end = lines.get(lines.size() - 1);
  137. if (end == 0)
  138. return true;
  139. return content[end - 1] != '\n';
  140. }
  141. /**
  142. * Get the text for a single line.
  143. *
  144. * @param i
  145. * index of the line to extract. Note this is 0-based, so line
  146. * number 1 is actually index 0.
  147. * @return the text for the line, without a trailing LF.
  148. */
  149. public String getString(int i) {
  150. return getString(i, i + 1, true);
  151. }
  152. /**
  153. * Get the raw text for a single line.
  154. *
  155. * @param i
  156. * index of the line to extract. Note this is 0-based, so line
  157. * number 1 is actually index 0.
  158. * @return the text for the line, without a trailing LF, as a
  159. * {@link ByteBuffer} that is backed by a slice of the
  160. * {@link #getRawContent() raw content}, with the buffer's position
  161. * on the start of the line and the limit at the end.
  162. * @since 5.12
  163. */
  164. public ByteBuffer getRawString(int i) {
  165. int s = getStart(i);
  166. int e = getEnd(i);
  167. if (e > 0 && content[e - 1] == '\n') {
  168. e--;
  169. }
  170. return ByteBuffer.wrap(content, s, e - s);
  171. }
  172. /**
  173. * Get the text for a region of lines.
  174. *
  175. * @param begin
  176. * index of the first line to extract. Note this is 0-based, so
  177. * line number 1 is actually index 0.
  178. * @param end
  179. * index of one past the last line to extract.
  180. * @param dropLF
  181. * if true the trailing LF ('\n') of the last returned line is
  182. * dropped, if present.
  183. * @return the text for lines {@code [begin, end)}.
  184. */
  185. public String getString(int begin, int end, boolean dropLF) {
  186. if (begin == end)
  187. return ""; //$NON-NLS-1$
  188. int s = getStart(begin);
  189. int e = getEnd(end - 1);
  190. if (dropLF && content[e - 1] == '\n')
  191. e--;
  192. return decode(s, e);
  193. }
  194. /**
  195. * Decode a region of the text into a String.
  196. *
  197. * The default implementation of this method tries to guess the character
  198. * set by considering UTF-8, the platform default, and falling back on
  199. * ISO-8859-1 if neither of those can correctly decode the region given.
  200. *
  201. * @param start
  202. * first byte of the content to decode.
  203. * @param end
  204. * one past the last byte of the content to decode.
  205. * @return the region {@code [start, end)} decoded as a String.
  206. */
  207. protected String decode(int start, int end) {
  208. return RawParseUtils.decode(content, start, end);
  209. }
  210. private int getStart(int i) {
  211. return lines.get(i + 1);
  212. }
  213. private int getEnd(int i) {
  214. return lines.get(i + 2);
  215. }
  216. /**
  217. * Determine heuristically whether a byte array represents binary (as
  218. * opposed to text) content.
  219. *
  220. * @param raw
  221. * the raw file content.
  222. * @return true if raw is likely to be a binary file, false otherwise
  223. */
  224. public static boolean isBinary(byte[] raw) {
  225. return isBinary(raw, raw.length);
  226. }
  227. /**
  228. * Determine heuristically whether the bytes contained in a stream
  229. * represents binary (as opposed to text) content.
  230. *
  231. * Note: Do not further use this stream after having called this method! The
  232. * stream may not be fully read and will be left at an unknown position
  233. * after consuming an unknown number of bytes. The caller is responsible for
  234. * closing the stream.
  235. *
  236. * @param raw
  237. * input stream containing the raw file content.
  238. * @return true if raw is likely to be a binary file, false otherwise
  239. * @throws java.io.IOException
  240. * if input stream could not be read
  241. */
  242. public static boolean isBinary(InputStream raw) throws IOException {
  243. final byte[] buffer = new byte[FIRST_FEW_BYTES];
  244. int cnt = 0;
  245. while (cnt < buffer.length) {
  246. final int n = raw.read(buffer, cnt, buffer.length - cnt);
  247. if (n == -1)
  248. break;
  249. cnt += n;
  250. }
  251. return isBinary(buffer, cnt);
  252. }
  253. /**
  254. * Determine heuristically whether a byte array represents binary (as
  255. * opposed to text) content.
  256. *
  257. * @param raw
  258. * the raw file content.
  259. * @param length
  260. * number of bytes in {@code raw} to evaluate. This should be
  261. * {@code raw.length} unless {@code raw} was over-allocated by
  262. * the caller.
  263. * @return true if raw is likely to be a binary file, false otherwise
  264. */
  265. public static boolean isBinary(byte[] raw, int length) {
  266. // Same heuristic as C Git
  267. if (length > FIRST_FEW_BYTES)
  268. length = FIRST_FEW_BYTES;
  269. for (int ptr = 0; ptr < length; ptr++)
  270. if (raw[ptr] == '\0')
  271. return true;
  272. return false;
  273. }
  274. /**
  275. * Determine heuristically whether a byte array represents text content
  276. * using CR-LF as line separator.
  277. *
  278. * @param raw
  279. * the raw file content.
  280. * @return {@code true} if raw is likely to be CR-LF delimited text,
  281. * {@code false} otherwise
  282. * @since 5.3
  283. */
  284. public static boolean isCrLfText(byte[] raw) {
  285. return isCrLfText(raw, raw.length);
  286. }
  287. /**
  288. * Determine heuristically whether the bytes contained in a stream represent
  289. * text content using CR-LF as line separator.
  290. *
  291. * Note: Do not further use this stream after having called this method! The
  292. * stream may not be fully read and will be left at an unknown position
  293. * after consuming an unknown number of bytes. The caller is responsible for
  294. * closing the stream.
  295. *
  296. * @param raw
  297. * input stream containing the raw file content.
  298. * @return {@code true} if raw is likely to be CR-LF delimited text,
  299. * {@code false} otherwise
  300. * @throws java.io.IOException
  301. * if input stream could not be read
  302. * @since 5.3
  303. */
  304. public static boolean isCrLfText(InputStream raw) throws IOException {
  305. byte[] buffer = new byte[FIRST_FEW_BYTES];
  306. int cnt = 0;
  307. while (cnt < buffer.length) {
  308. int n = raw.read(buffer, cnt, buffer.length - cnt);
  309. if (n == -1) {
  310. break;
  311. }
  312. cnt += n;
  313. }
  314. return isCrLfText(buffer, cnt);
  315. }
  316. /**
  317. * Determine heuristically whether a byte array represents text content
  318. * using CR-LF as line separator.
  319. *
  320. * @param raw
  321. * the raw file content.
  322. * @param length
  323. * number of bytes in {@code raw} to evaluate.
  324. * @return {@code true} if raw is likely to be CR-LF delimited text,
  325. * {@code false} otherwise
  326. * @since 5.3
  327. */
  328. public static boolean isCrLfText(byte[] raw, int length) {
  329. boolean has_crlf = false;
  330. for (int ptr = 0; ptr < length - 1; ptr++) {
  331. if (raw[ptr] == '\0') {
  332. return false; // binary
  333. } else if (raw[ptr] == '\r' && raw[ptr + 1] == '\n') {
  334. has_crlf = true;
  335. }
  336. }
  337. return has_crlf;
  338. }
  339. /**
  340. * Get the line delimiter for the first line.
  341. *
  342. * @since 2.0
  343. * @return the line delimiter or <code>null</code>
  344. */
  345. public String getLineDelimiter() {
  346. if (size() == 0) {
  347. return null;
  348. }
  349. int e = getEnd(0);
  350. if (content[e - 1] != '\n') {
  351. return null;
  352. }
  353. if (content.length > 1 && e > 1 && content[e - 2] == '\r') {
  354. return "\r\n"; //$NON-NLS-1$
  355. }
  356. return "\n"; //$NON-NLS-1$
  357. }
  358. /**
  359. * Read a blob object into RawText, or throw BinaryBlobException if the blob
  360. * is binary.
  361. *
  362. * @param ldr
  363. * the ObjectLoader for the blob
  364. * @param threshold
  365. * if the blob is larger than this size, it is always assumed to
  366. * be binary.
  367. * @since 4.10
  368. * @return the RawText representing the blob.
  369. * @throws org.eclipse.jgit.errors.BinaryBlobException
  370. * if the blob contains binary data.
  371. * @throws java.io.IOException
  372. * if the input could not be read.
  373. */
  374. public static RawText load(ObjectLoader ldr, int threshold)
  375. throws IOException, BinaryBlobException {
  376. long sz = ldr.getSize();
  377. if (sz > threshold) {
  378. throw new BinaryBlobException();
  379. }
  380. if (sz <= FIRST_FEW_BYTES) {
  381. byte[] data = ldr.getCachedBytes(FIRST_FEW_BYTES);
  382. if (isBinary(data)) {
  383. throw new BinaryBlobException();
  384. }
  385. return new RawText(data);
  386. }
  387. byte[] head = new byte[FIRST_FEW_BYTES];
  388. try (InputStream stream = ldr.openStream()) {
  389. int off = 0;
  390. int left = head.length;
  391. while (left > 0) {
  392. int n = stream.read(head, off, left);
  393. if (n < 0) {
  394. throw new EOFException();
  395. }
  396. left -= n;
  397. while (n > 0) {
  398. if (head[off] == '\0') {
  399. throw new BinaryBlobException();
  400. }
  401. off++;
  402. n--;
  403. }
  404. }
  405. byte[] data;
  406. try {
  407. data = new byte[(int)sz];
  408. } catch (OutOfMemoryError e) {
  409. throw new LargeObjectException.OutOfMemory(e);
  410. }
  411. System.arraycopy(head, 0, data, 0, head.length);
  412. IO.readFully(stream, data, off, (int) (sz-off));
  413. return new RawText(data, RawParseUtils.lineMapOrBinary(data, 0, (int) sz));
  414. }
  415. }
  416. }