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.

AddCommand.java 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2010, Stefan Lay <stefan.lay@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  46. import static org.eclipse.jgit.lib.FileMode.GITLINK;
  47. import static org.eclipse.jgit.lib.FileMode.TYPE_GITLINK;
  48. import static org.eclipse.jgit.lib.FileMode.TYPE_TREE;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.util.Collection;
  52. import java.util.LinkedList;
  53. import org.eclipse.jgit.api.errors.FilterFailedException;
  54. import org.eclipse.jgit.api.errors.GitAPIException;
  55. import org.eclipse.jgit.api.errors.JGitInternalException;
  56. import org.eclipse.jgit.api.errors.NoFilepatternException;
  57. import org.eclipse.jgit.dircache.DirCache;
  58. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  59. import org.eclipse.jgit.dircache.DirCacheBuilder;
  60. import org.eclipse.jgit.dircache.DirCacheEntry;
  61. import org.eclipse.jgit.dircache.DirCacheIterator;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.lib.FileMode;
  64. import org.eclipse.jgit.lib.ObjectId;
  65. import org.eclipse.jgit.lib.ObjectInserter;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.treewalk.FileTreeIterator;
  68. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  69. import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
  70. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  71. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  72. /**
  73. * A class used to execute a {@code Add} command. It has setters for all
  74. * supported options and arguments of this command and a {@link #call()} method
  75. * to finally execute the command. Each instance of this class should only be
  76. * used for one invocation of the command (means: one call to {@link #call()})
  77. *
  78. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-add.html"
  79. * >Git documentation about Add</a>
  80. */
  81. public class AddCommand extends GitCommand<DirCache> {
  82. private Collection<String> filepatterns;
  83. private WorkingTreeIterator workingTreeIterator;
  84. private boolean update = false;
  85. /**
  86. *
  87. * @param repo
  88. */
  89. public AddCommand(Repository repo) {
  90. super(repo);
  91. filepatterns = new LinkedList<String>();
  92. }
  93. /**
  94. * Add a path to a file/directory whose content should be added.
  95. * <p>
  96. * A directory name (e.g. <code>dir</code> to add <code>dir/file1</code> and
  97. * <code>dir/file2</code>) can also be given to add all files in the
  98. * directory, recursively. Fileglobs (e.g. *.c) are not yet supported.
  99. *
  100. * @param filepattern
  101. * repository-relative path of file/directory to add (with
  102. * <code>/</code> as separator)
  103. * @return {@code this}
  104. */
  105. public AddCommand addFilepattern(String filepattern) {
  106. checkCallable();
  107. filepatterns.add(filepattern);
  108. return this;
  109. }
  110. /**
  111. * Allow clients to provide their own implementation of a FileTreeIterator
  112. * @param f
  113. * @return {@code this}
  114. */
  115. public AddCommand setWorkingTreeIterator(WorkingTreeIterator f) {
  116. workingTreeIterator = f;
  117. return this;
  118. }
  119. /**
  120. * Executes the {@code Add} command. Each instance of this class should only
  121. * be used for one invocation of the command. Don't call this method twice
  122. * on an instance.
  123. *
  124. * @return the DirCache after Add
  125. */
  126. public DirCache call() throws GitAPIException, NoFilepatternException {
  127. if (filepatterns.isEmpty())
  128. throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
  129. checkCallable();
  130. DirCache dc = null;
  131. boolean addAll = filepatterns.contains("."); //$NON-NLS-1$
  132. try (ObjectInserter inserter = repo.newObjectInserter();
  133. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
  134. tw.setOperationType(OperationType.CHECKIN_OP);
  135. dc = repo.lockDirCache();
  136. DirCacheBuilder builder = dc.builder();
  137. tw.addTree(new DirCacheBuildIterator(builder));
  138. if (workingTreeIterator == null)
  139. workingTreeIterator = new FileTreeIterator(repo);
  140. workingTreeIterator.setDirCacheIterator(tw, 0);
  141. tw.addTree(workingTreeIterator);
  142. if (!addAll)
  143. tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
  144. byte[] lastAdded = null;
  145. while (tw.next()) {
  146. DirCacheIterator c = tw.getTree(0, DirCacheIterator.class);
  147. WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
  148. if (c == null && f != null && f.isEntryIgnored()) {
  149. // file is not in index but is ignored, do nothing
  150. continue;
  151. } else if (c == null && update) {
  152. // Only update of existing entries was requested.
  153. continue;
  154. }
  155. DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null;
  156. if (entry != null && entry.getStage() > 0
  157. && lastAdded != null
  158. && lastAdded.length == tw.getPathLength()
  159. && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) {
  160. // In case of an existing merge conflict the
  161. // DirCacheBuildIterator iterates over all stages of
  162. // this path, we however want to add only one
  163. // new DirCacheEntry per path.
  164. continue;
  165. }
  166. if (tw.isSubtree() && !tw.isDirectoryFileConflict()) {
  167. tw.enterSubtree();
  168. continue;
  169. }
  170. if (f == null) { // working tree file does not exist
  171. if (entry != null
  172. && (!update || GITLINK == entry.getFileMode())) {
  173. builder.add(entry);
  174. }
  175. continue;
  176. }
  177. if (entry != null && entry.isAssumeValid()) {
  178. // Index entry is marked assume valid. Even though
  179. // the user specified the file to be added JGit does
  180. // not consider the file for addition.
  181. builder.add(entry);
  182. continue;
  183. }
  184. if ((f.getEntryRawMode() == TYPE_TREE
  185. && f.getIndexFileMode(c) != FileMode.GITLINK) ||
  186. (f.getEntryRawMode() == TYPE_GITLINK
  187. && f.getIndexFileMode(c) == FileMode.TREE)) {
  188. // Index entry exists and is symlink, gitlink or file,
  189. // otherwise the tree would have been entered above.
  190. // Replace the index entry by diving into tree of files.
  191. tw.enterSubtree();
  192. continue;
  193. }
  194. byte[] path = tw.getRawPath();
  195. if (entry == null || entry.getStage() > 0) {
  196. entry = new DirCacheEntry(path);
  197. }
  198. FileMode mode = f.getIndexFileMode(c);
  199. entry.setFileMode(mode);
  200. if (GITLINK != mode) {
  201. entry.setLength(f.getEntryLength());
  202. entry.setLastModified(f.getEntryLastModified());
  203. long len = f.getEntryContentLength();
  204. // We read and filter the content multiple times.
  205. // f.getEntryContentLength() reads and filters the input and
  206. // inserter.insert(...) does it again. That's because an
  207. // ObjectInserter needs to know the length before it starts
  208. // inserting. TODO: Fix this by using Buffers.
  209. try (InputStream in = f.openEntryStream()) {
  210. ObjectId id = inserter.insert(OBJ_BLOB, len, in);
  211. entry.setObjectId(id);
  212. }
  213. } else {
  214. entry.setLength(0);
  215. entry.setLastModified(0);
  216. entry.setObjectId(f.getEntryObjectId());
  217. }
  218. builder.add(entry);
  219. lastAdded = path;
  220. }
  221. inserter.flush();
  222. builder.commit();
  223. setCallable(false);
  224. } catch (IOException e) {
  225. Throwable cause = e.getCause();
  226. if (cause != null && cause instanceof FilterFailedException)
  227. throw (FilterFailedException) cause;
  228. throw new JGitInternalException(
  229. JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
  230. } finally {
  231. if (dc != null)
  232. dc.unlock();
  233. }
  234. return dc;
  235. }
  236. /**
  237. * @param update
  238. * If set to true, the command only matches {@code filepattern}
  239. * against already tracked files in the index rather than the
  240. * working tree. That means that it will never stage new files,
  241. * but that it will stage modified new contents of tracked files
  242. * and that it will remove files from the index if the
  243. * corresponding files in the working tree have been removed.
  244. * In contrast to the git command line a {@code filepattern} must
  245. * exist also if update is set to true as there is no
  246. * concept of a working directory here.
  247. *
  248. * @return {@code this}
  249. */
  250. public AddCommand setUpdate(boolean update) {
  251. this.update = update;
  252. return this;
  253. }
  254. /**
  255. * @return is the parameter update is set
  256. */
  257. public boolean isUpdate() {
  258. return update;
  259. }
  260. }