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

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