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.

ApplyCommand.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Copyright (C) 2011, 2012, IBM Corporation and others.
  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.api;
  44. import java.io.File;
  45. import java.io.FileOutputStream;
  46. import java.io.FileWriter;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.nio.file.StandardCopyOption;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.List;
  53. import org.eclipse.jgit.api.errors.GitAPIException;
  54. import org.eclipse.jgit.api.errors.PatchApplyException;
  55. import org.eclipse.jgit.api.errors.PatchFormatException;
  56. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  57. import org.eclipse.jgit.diff.RawText;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.lib.Repository;
  60. import org.eclipse.jgit.patch.FileHeader;
  61. import org.eclipse.jgit.patch.HunkHeader;
  62. import org.eclipse.jgit.patch.Patch;
  63. import org.eclipse.jgit.util.FileUtils;
  64. import org.eclipse.jgit.util.IO;
  65. /**
  66. * Apply a patch to files and/or to the index.
  67. *
  68. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-apply.html"
  69. * >Git documentation about apply</a>
  70. * @since 2.0
  71. */
  72. public class ApplyCommand extends GitCommand<ApplyResult> {
  73. private InputStream in;
  74. /**
  75. * Constructs the command if the patch is to be applied to the index.
  76. *
  77. * @param repo
  78. */
  79. ApplyCommand(Repository repo) {
  80. super(repo);
  81. }
  82. /**
  83. * @param in
  84. * the patch to apply
  85. * @return this instance
  86. */
  87. public ApplyCommand setPatch(InputStream in) {
  88. checkCallable();
  89. this.in = in;
  90. return this;
  91. }
  92. /**
  93. * Executes the {@code ApplyCommand} command with all the options and
  94. * parameters collected by the setter methods (e.g.
  95. * {@link #setPatch(InputStream)} of this class. Each instance of this class
  96. * should only be used for one invocation of the command. Don't call this
  97. * method twice on an instance.
  98. *
  99. * @return an {@link ApplyResult} object representing the command result
  100. * @throws GitAPIException
  101. * @throws PatchFormatException
  102. * @throws PatchApplyException
  103. */
  104. public ApplyResult call() throws GitAPIException, PatchFormatException,
  105. PatchApplyException {
  106. checkCallable();
  107. ApplyResult r = new ApplyResult();
  108. try {
  109. final Patch p = new Patch();
  110. try {
  111. p.parse(in);
  112. } finally {
  113. in.close();
  114. }
  115. if (!p.getErrors().isEmpty())
  116. throw new PatchFormatException(p.getErrors());
  117. for (FileHeader fh : p.getFiles()) {
  118. ChangeType type = fh.getChangeType();
  119. File f = null;
  120. switch (type) {
  121. case ADD:
  122. f = getFile(fh.getNewPath(), true);
  123. apply(f, fh);
  124. break;
  125. case MODIFY:
  126. f = getFile(fh.getOldPath(), false);
  127. apply(f, fh);
  128. break;
  129. case DELETE:
  130. f = getFile(fh.getOldPath(), false);
  131. if (!f.delete())
  132. throw new PatchApplyException(MessageFormat.format(
  133. JGitText.get().cannotDeleteFile, f));
  134. break;
  135. case RENAME:
  136. f = getFile(fh.getOldPath(), false);
  137. File dest = getFile(fh.getNewPath(), false);
  138. try {
  139. FileUtils.rename(f, dest,
  140. StandardCopyOption.ATOMIC_MOVE);
  141. } catch (IOException e) {
  142. throw new PatchApplyException(MessageFormat.format(
  143. JGitText.get().renameFileFailed, f, dest), e);
  144. }
  145. break;
  146. case COPY:
  147. f = getFile(fh.getOldPath(), false);
  148. byte[] bs = IO.readFully(f);
  149. FileOutputStream fos = new FileOutputStream(getFile(
  150. fh.getNewPath(),
  151. true));
  152. try {
  153. fos.write(bs);
  154. } finally {
  155. fos.close();
  156. }
  157. }
  158. r.addUpdatedFile(f);
  159. }
  160. } catch (IOException e) {
  161. throw new PatchApplyException(MessageFormat.format(
  162. JGitText.get().patchApplyException, e.getMessage()), e);
  163. }
  164. setCallable(false);
  165. return r;
  166. }
  167. private File getFile(String path, boolean create)
  168. throws PatchApplyException {
  169. File f = new File(getRepository().getWorkTree(), path);
  170. if (create)
  171. try {
  172. File parent = f.getParentFile();
  173. FileUtils.mkdirs(parent, true);
  174. FileUtils.createNewFile(f);
  175. } catch (IOException e) {
  176. throw new PatchApplyException(MessageFormat.format(
  177. JGitText.get().createNewFileFailed, f), e);
  178. }
  179. return f;
  180. }
  181. /**
  182. * @param f
  183. * @param fh
  184. * @throws IOException
  185. * @throws PatchApplyException
  186. */
  187. private void apply(File f, FileHeader fh)
  188. throws IOException, PatchApplyException {
  189. RawText rt = new RawText(f);
  190. List<String> oldLines = new ArrayList<String>(rt.size());
  191. for (int i = 0; i < rt.size(); i++)
  192. oldLines.add(rt.getString(i));
  193. List<String> newLines = new ArrayList<String>(oldLines);
  194. for (HunkHeader hh : fh.getHunks()) {
  195. StringBuilder hunk = new StringBuilder();
  196. for (int j = hh.getStartOffset(); j < hh.getEndOffset(); j++)
  197. hunk.append((char) hh.getBuffer()[j]);
  198. RawText hrt = new RawText(hunk.toString().getBytes());
  199. List<String> hunkLines = new ArrayList<String>(hrt.size());
  200. for (int i = 0; i < hrt.size(); i++)
  201. hunkLines.add(hrt.getString(i));
  202. int pos = 0;
  203. for (int j = 1; j < hunkLines.size(); j++) {
  204. String hunkLine = hunkLines.get(j);
  205. switch (hunkLine.charAt(0)) {
  206. case ' ':
  207. if (!newLines.get(hh.getNewStartLine() - 1 + pos).equals(
  208. hunkLine.substring(1))) {
  209. throw new PatchApplyException(MessageFormat.format(
  210. JGitText.get().patchApplyException, hh));
  211. }
  212. pos++;
  213. break;
  214. case '-':
  215. if (!newLines.get(hh.getNewStartLine() - 1 + pos).equals(
  216. hunkLine.substring(1))) {
  217. throw new PatchApplyException(MessageFormat.format(
  218. JGitText.get().patchApplyException, hh));
  219. }
  220. newLines.remove(hh.getNewStartLine() - 1 + pos);
  221. break;
  222. case '+':
  223. newLines.add(hh.getNewStartLine() - 1 + pos,
  224. hunkLine.substring(1));
  225. pos++;
  226. break;
  227. }
  228. }
  229. }
  230. if (!isNoNewlineAtEndOfFile(fh))
  231. newLines.add(""); //$NON-NLS-1$
  232. if (!rt.isMissingNewlineAtEnd())
  233. oldLines.add(""); //$NON-NLS-1$
  234. if (!isChanged(oldLines, newLines))
  235. return; // don't touch the file
  236. StringBuilder sb = new StringBuilder();
  237. for (String l : newLines) {
  238. // don't bother handling line endings - if it was windows, the \r is
  239. // still there!
  240. sb.append(l).append('\n');
  241. }
  242. sb.deleteCharAt(sb.length() - 1);
  243. FileWriter fw = new FileWriter(f);
  244. fw.write(sb.toString());
  245. fw.close();
  246. }
  247. private static boolean isChanged(List<String> ol, List<String> nl) {
  248. if (ol.size() != nl.size())
  249. return true;
  250. for (int i = 0; i < ol.size(); i++)
  251. if (!ol.get(i).equals(nl.get(i)))
  252. return true;
  253. return false;
  254. }
  255. private boolean isNoNewlineAtEndOfFile(FileHeader fh) {
  256. HunkHeader lastHunk = fh.getHunks().get(fh.getHunks().size() - 1);
  257. RawText lhrt = new RawText(lastHunk.getBuffer());
  258. return lhrt.getString(lhrt.size() - 1).equals(
  259. "\\ No newline at end of file"); //$NON-NLS-1$
  260. }
  261. }