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.6KB

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