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

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