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

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