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.

Patch.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.patch;
  44. import static org.eclipse.jgit.lib.Constants.encodeASCII;
  45. import static org.eclipse.jgit.patch.FileHeader.isHunkHdr;
  46. import static org.eclipse.jgit.patch.FileHeader.NEW_NAME;
  47. import static org.eclipse.jgit.patch.FileHeader.OLD_NAME;
  48. import static org.eclipse.jgit.util.RawParseUtils.match;
  49. import static org.eclipse.jgit.util.RawParseUtils.nextLF;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.util.ArrayList;
  53. import java.util.List;
  54. import org.eclipse.jgit.internal.JGitText;
  55. import org.eclipse.jgit.util.TemporaryBuffer;
  56. /** A parsed collection of {@link FileHeader}s from a unified diff patch file */
  57. public class Patch {
  58. static final byte[] DIFF_GIT = encodeASCII("diff --git ");
  59. private static final byte[] DIFF_CC = encodeASCII("diff --cc ");
  60. private static final byte[] DIFF_COMBINED = encodeASCII("diff --combined ");
  61. private static final byte[][] BIN_HEADERS = new byte[][] {
  62. encodeASCII("Binary files "), encodeASCII("Files "), };
  63. private static final byte[] BIN_TRAILER = encodeASCII(" differ\n");
  64. private static final byte[] GIT_BINARY = encodeASCII("GIT binary patch\n");
  65. static final byte[] SIG_FOOTER = encodeASCII("-- \n");
  66. /** The files, in the order they were parsed out of the input. */
  67. private final List<FileHeader> files;
  68. /** Formatting errors, if any were identified. */
  69. private final List<FormatError> errors;
  70. /** Create an empty patch. */
  71. public Patch() {
  72. files = new ArrayList<FileHeader>();
  73. errors = new ArrayList<FormatError>(0);
  74. }
  75. /**
  76. * Add a single file to this patch.
  77. * <p>
  78. * Typically files should be added by parsing the text through one of this
  79. * class's parse methods.
  80. *
  81. * @param fh
  82. * the header of the file.
  83. */
  84. public void addFile(final FileHeader fh) {
  85. files.add(fh);
  86. }
  87. /** @return list of files described in the patch, in occurrence order. */
  88. public List<? extends FileHeader> getFiles() {
  89. return files;
  90. }
  91. /**
  92. * Add a formatting error to this patch script.
  93. *
  94. * @param err
  95. * the error description.
  96. */
  97. public void addError(final FormatError err) {
  98. errors.add(err);
  99. }
  100. /** @return collection of formatting errors, if any. */
  101. public List<FormatError> getErrors() {
  102. return errors;
  103. }
  104. /**
  105. * Parse a patch received from an InputStream.
  106. * <p>
  107. * Multiple parse calls on the same instance will concatenate the patch
  108. * data, but each parse input must start with a valid file header (don't
  109. * split a single file across parse calls).
  110. *
  111. * @param is
  112. * the stream to read the patch data from. The stream is read
  113. * until EOF is reached.
  114. * @throws IOException
  115. * there was an error reading from the input stream.
  116. */
  117. public void parse(final InputStream is) throws IOException {
  118. final byte[] buf = readFully(is);
  119. parse(buf, 0, buf.length);
  120. }
  121. private static byte[] readFully(final InputStream is) throws IOException {
  122. final TemporaryBuffer b = new TemporaryBuffer.LocalFile();
  123. try {
  124. b.copy(is);
  125. b.close();
  126. return b.toByteArray();
  127. } finally {
  128. b.destroy();
  129. }
  130. }
  131. /**
  132. * Parse a patch stored in a byte[].
  133. * <p>
  134. * Multiple parse calls on the same instance will concatenate the patch
  135. * data, but each parse input must start with a valid file header (don't
  136. * split a single file across parse calls).
  137. *
  138. * @param buf
  139. * the buffer to parse.
  140. * @param ptr
  141. * starting position to parse from.
  142. * @param end
  143. * 1 past the last position to end parsing. The total length to
  144. * be parsed is <code>end - ptr</code>.
  145. */
  146. public void parse(final byte[] buf, int ptr, final int end) {
  147. while (ptr < end)
  148. ptr = parseFile(buf, ptr, end);
  149. }
  150. private int parseFile(final byte[] buf, int c, final int end) {
  151. while (c < end) {
  152. if (isHunkHdr(buf, c, end) >= 1) {
  153. // If we find a disconnected hunk header we might
  154. // have missed a file header previously. The hunk
  155. // isn't valid without knowing where it comes from.
  156. //
  157. error(buf, c, JGitText.get().hunkDisconnectedFromFile);
  158. c = nextLF(buf, c);
  159. continue;
  160. }
  161. // Valid git style patch?
  162. //
  163. if (match(buf, c, DIFF_GIT) >= 0)
  164. return parseDiffGit(buf, c, end);
  165. if (match(buf, c, DIFF_CC) >= 0)
  166. return parseDiffCombined(DIFF_CC, buf, c, end);
  167. if (match(buf, c, DIFF_COMBINED) >= 0)
  168. return parseDiffCombined(DIFF_COMBINED, buf, c, end);
  169. // Junk between files? Leading junk? Traditional
  170. // (non-git generated) patch?
  171. //
  172. final int n = nextLF(buf, c);
  173. if (n >= end) {
  174. // Patches cannot be only one line long. This must be
  175. // trailing junk that we should ignore.
  176. //
  177. return end;
  178. }
  179. if (n - c < 6) {
  180. // A valid header must be at least 6 bytes on the
  181. // first line, e.g. "--- a/b\n".
  182. //
  183. c = n;
  184. continue;
  185. }
  186. if (match(buf, c, OLD_NAME) >= 0 && match(buf, n, NEW_NAME) >= 0) {
  187. // Probably a traditional patch. Ensure we have at least
  188. // a "@@ -0,0" smelling line next. We only check the "@@ -".
  189. //
  190. final int f = nextLF(buf, n);
  191. if (f >= end)
  192. return end;
  193. if (isHunkHdr(buf, f, end) == 1)
  194. return parseTraditionalPatch(buf, c, end);
  195. }
  196. c = n;
  197. }
  198. return c;
  199. }
  200. private int parseDiffGit(final byte[] buf, final int start, final int end) {
  201. final FileHeader fh = new FileHeader(buf, start);
  202. int ptr = fh.parseGitFileName(start + DIFF_GIT.length, end);
  203. if (ptr < 0)
  204. return skipFile(buf, start);
  205. ptr = fh.parseGitHeaders(ptr, end);
  206. ptr = parseHunks(fh, ptr, end);
  207. fh.endOffset = ptr;
  208. addFile(fh);
  209. return ptr;
  210. }
  211. private int parseDiffCombined(final byte[] hdr, final byte[] buf,
  212. final int start, final int end) {
  213. final CombinedFileHeader fh = new CombinedFileHeader(buf, start);
  214. int ptr = fh.parseGitFileName(start + hdr.length, end);
  215. if (ptr < 0)
  216. return skipFile(buf, start);
  217. ptr = fh.parseGitHeaders(ptr, end);
  218. ptr = parseHunks(fh, ptr, end);
  219. fh.endOffset = ptr;
  220. addFile(fh);
  221. return ptr;
  222. }
  223. private int parseTraditionalPatch(final byte[] buf, final int start,
  224. final int end) {
  225. final FileHeader fh = new FileHeader(buf, start);
  226. int ptr = fh.parseTraditionalHeaders(start, end);
  227. ptr = parseHunks(fh, ptr, end);
  228. fh.endOffset = ptr;
  229. addFile(fh);
  230. return ptr;
  231. }
  232. private static int skipFile(final byte[] buf, int ptr) {
  233. ptr = nextLF(buf, ptr);
  234. if (match(buf, ptr, OLD_NAME) >= 0)
  235. ptr = nextLF(buf, ptr);
  236. return ptr;
  237. }
  238. private int parseHunks(final FileHeader fh, int c, final int end) {
  239. final byte[] buf = fh.buf;
  240. while (c < end) {
  241. // If we see a file header at this point, we have all of the
  242. // hunks for our current file. We should stop and report back
  243. // with this position so it can be parsed again later.
  244. //
  245. if (match(buf, c, DIFF_GIT) >= 0)
  246. break;
  247. if (match(buf, c, DIFF_CC) >= 0)
  248. break;
  249. if (match(buf, c, DIFF_COMBINED) >= 0)
  250. break;
  251. if (match(buf, c, OLD_NAME) >= 0)
  252. break;
  253. if (match(buf, c, NEW_NAME) >= 0)
  254. break;
  255. if (isHunkHdr(buf, c, end) == fh.getParentCount()) {
  256. final HunkHeader h = fh.newHunkHeader(c);
  257. h.parseHeader();
  258. c = h.parseBody(this, end);
  259. h.endOffset = c;
  260. fh.addHunk(h);
  261. if (c < end) {
  262. switch (buf[c]) {
  263. case '@':
  264. case 'd':
  265. case '\n':
  266. break;
  267. default:
  268. if (match(buf, c, SIG_FOOTER) < 0)
  269. warn(buf, c, JGitText.get().unexpectedHunkTrailer);
  270. }
  271. }
  272. continue;
  273. }
  274. final int eol = nextLF(buf, c);
  275. if (fh.getHunks().isEmpty() && match(buf, c, GIT_BINARY) >= 0) {
  276. fh.patchType = FileHeader.PatchType.GIT_BINARY;
  277. return parseGitBinary(fh, eol, end);
  278. }
  279. if (fh.getHunks().isEmpty() && BIN_TRAILER.length < eol - c
  280. && match(buf, eol - BIN_TRAILER.length, BIN_TRAILER) >= 0
  281. && matchAny(buf, c, BIN_HEADERS)) {
  282. // The patch is a binary file diff, with no deltas.
  283. //
  284. fh.patchType = FileHeader.PatchType.BINARY;
  285. return eol;
  286. }
  287. // Skip this line and move to the next. Its probably garbage
  288. // after the last hunk of a file.
  289. //
  290. c = eol;
  291. }
  292. if (fh.getHunks().isEmpty()
  293. && fh.getPatchType() == FileHeader.PatchType.UNIFIED
  294. && !fh.hasMetaDataChanges()) {
  295. // Hmm, an empty patch? If there is no metadata here we
  296. // really have a binary patch that we didn't notice above.
  297. //
  298. fh.patchType = FileHeader.PatchType.BINARY;
  299. }
  300. return c;
  301. }
  302. private int parseGitBinary(final FileHeader fh, int c, final int end) {
  303. final BinaryHunk postImage = new BinaryHunk(fh, c);
  304. final int nEnd = postImage.parseHunk(c, end);
  305. if (nEnd < 0) {
  306. // Not a binary hunk.
  307. //
  308. error(fh.buf, c, JGitText.get().missingForwardImageInGITBinaryPatch);
  309. return c;
  310. }
  311. c = nEnd;
  312. postImage.endOffset = c;
  313. fh.forwardBinaryHunk = postImage;
  314. final BinaryHunk preImage = new BinaryHunk(fh, c);
  315. final int oEnd = preImage.parseHunk(c, end);
  316. if (oEnd >= 0) {
  317. c = oEnd;
  318. preImage.endOffset = c;
  319. fh.reverseBinaryHunk = preImage;
  320. }
  321. return c;
  322. }
  323. void warn(final byte[] buf, final int ptr, final String msg) {
  324. addError(new FormatError(buf, ptr, FormatError.Severity.WARNING, msg));
  325. }
  326. void error(final byte[] buf, final int ptr, final String msg) {
  327. addError(new FormatError(buf, ptr, FormatError.Severity.ERROR, msg));
  328. }
  329. private static boolean matchAny(final byte[] buf, final int c,
  330. final byte[][] srcs) {
  331. for (final byte[] s : srcs) {
  332. if (match(buf, c, s) >= 0)
  333. return true;
  334. }
  335. return false;
  336. }
  337. }