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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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.time.Instant;
  52. import java.util.Collection;
  53. import java.util.LinkedList;
  54. import org.eclipse.jgit.api.errors.FilterFailedException;
  55. import org.eclipse.jgit.api.errors.GitAPIException;
  56. import org.eclipse.jgit.api.errors.JGitInternalException;
  57. import org.eclipse.jgit.api.errors.NoFilepatternException;
  58. import org.eclipse.jgit.dircache.DirCache;
  59. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  60. import org.eclipse.jgit.dircache.DirCacheBuilder;
  61. import org.eclipse.jgit.dircache.DirCacheEntry;
  62. import org.eclipse.jgit.dircache.DirCacheIterator;
  63. import org.eclipse.jgit.internal.JGitText;
  64. import org.eclipse.jgit.lib.FileMode;
  65. import org.eclipse.jgit.lib.ObjectId;
  66. import org.eclipse.jgit.lib.ObjectInserter;
  67. import org.eclipse.jgit.lib.Repository;
  68. import org.eclipse.jgit.treewalk.FileTreeIterator;
  69. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  70. import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
  71. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  72. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  73. /**
  74. * A class used to execute a {@code Add} command. It has setters for all
  75. * supported options and arguments of this command and a {@link #call()} method
  76. * to finally execute the command. Each instance of this class should only be
  77. * used for one invocation of the command (means: one call to {@link #call()})
  78. *
  79. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-add.html"
  80. * >Git documentation about Add</a>
  81. */
  82. public class AddCommand extends GitCommand<DirCache> {
  83. private Collection<String> filepatterns;
  84. private WorkingTreeIterator workingTreeIterator;
  85. private boolean update = false;
  86. /**
  87. * Constructor for AddCommand
  88. *
  89. * @param repo
  90. * the {@link org.eclipse.jgit.lib.Repository}
  91. */
  92. public AddCommand(Repository repo) {
  93. super(repo);
  94. filepatterns = new LinkedList<>();
  95. }
  96. /**
  97. * Add a path to a file/directory whose content should be added.
  98. * <p>
  99. * A directory name (e.g. <code>dir</code> to add <code>dir/file1</code> and
  100. * <code>dir/file2</code>) can also be given to add all files in the
  101. * directory, recursively. Fileglobs (e.g. *.c) are not yet supported.
  102. *
  103. * @param filepattern
  104. * repository-relative path of file/directory to add (with
  105. * <code>/</code> as separator)
  106. * @return {@code this}
  107. */
  108. public AddCommand addFilepattern(String filepattern) {
  109. checkCallable();
  110. filepatterns.add(filepattern);
  111. return this;
  112. }
  113. /**
  114. * Allow clients to provide their own implementation of a FileTreeIterator
  115. *
  116. * @param f
  117. * a {@link org.eclipse.jgit.treewalk.WorkingTreeIterator}
  118. * object.
  119. * @return {@code this}
  120. */
  121. public AddCommand setWorkingTreeIterator(WorkingTreeIterator f) {
  122. workingTreeIterator = f;
  123. return this;
  124. }
  125. /**
  126. * {@inheritDoc}
  127. * <p>
  128. * Executes the {@code Add} command. Each instance of this class should only
  129. * be used for one invocation of the command. Don't call this method twice
  130. * on an instance.
  131. */
  132. @Override
  133. public DirCache call() throws GitAPIException, NoFilepatternException {
  134. if (filepatterns.isEmpty())
  135. throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
  136. checkCallable();
  137. DirCache dc = null;
  138. boolean addAll = filepatterns.contains("."); //$NON-NLS-1$
  139. try (ObjectInserter inserter = repo.newObjectInserter();
  140. NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
  141. tw.setOperationType(OperationType.CHECKIN_OP);
  142. dc = repo.lockDirCache();
  143. DirCacheBuilder builder = dc.builder();
  144. tw.addTree(new DirCacheBuildIterator(builder));
  145. if (workingTreeIterator == null)
  146. workingTreeIterator = new FileTreeIterator(repo);
  147. workingTreeIterator.setDirCacheIterator(tw, 0);
  148. tw.addTree(workingTreeIterator);
  149. if (!addAll)
  150. tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
  151. byte[] lastAdded = null;
  152. while (tw.next()) {
  153. DirCacheIterator c = tw.getTree(0, DirCacheIterator.class);
  154. WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
  155. if (c == null && f != null && f.isEntryIgnored()) {
  156. // file is not in index but is ignored, do nothing
  157. continue;
  158. } else if (c == null && update) {
  159. // Only update of existing entries was requested.
  160. continue;
  161. }
  162. DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null;
  163. if (entry != null && entry.getStage() > 0
  164. && lastAdded != null
  165. && lastAdded.length == tw.getPathLength()
  166. && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) {
  167. // In case of an existing merge conflict the
  168. // DirCacheBuildIterator iterates over all stages of
  169. // this path, we however want to add only one
  170. // new DirCacheEntry per path.
  171. continue;
  172. }
  173. if (tw.isSubtree() && !tw.isDirectoryFileConflict()) {
  174. tw.enterSubtree();
  175. continue;
  176. }
  177. if (f == null) { // working tree file does not exist
  178. if (entry != null
  179. && (!update || GITLINK == entry.getFileMode())) {
  180. builder.add(entry);
  181. }
  182. continue;
  183. }
  184. if (entry != null && entry.isAssumeValid()) {
  185. // Index entry is marked assume valid. Even though
  186. // the user specified the file to be added JGit does
  187. // not consider the file for addition.
  188. builder.add(entry);
  189. continue;
  190. }
  191. if ((f.getEntryRawMode() == TYPE_TREE
  192. && f.getIndexFileMode(c) != FileMode.GITLINK) ||
  193. (f.getEntryRawMode() == TYPE_GITLINK
  194. && f.getIndexFileMode(c) == FileMode.TREE)) {
  195. // Index entry exists and is symlink, gitlink or file,
  196. // otherwise the tree would have been entered above.
  197. // Replace the index entry by diving into tree of files.
  198. tw.enterSubtree();
  199. continue;
  200. }
  201. byte[] path = tw.getRawPath();
  202. if (entry == null || entry.getStage() > 0) {
  203. entry = new DirCacheEntry(path);
  204. }
  205. FileMode mode = f.getIndexFileMode(c);
  206. entry.setFileMode(mode);
  207. if (GITLINK != mode) {
  208. entry.setLength(f.getEntryLength());
  209. entry.setLastModified(f.getEntryLastModifiedInstant());
  210. long len = f.getEntryContentLength();
  211. // We read and filter the content multiple times.
  212. // f.getEntryContentLength() reads and filters the input and
  213. // inserter.insert(...) does it again. That's because an
  214. // ObjectInserter needs to know the length before it starts
  215. // inserting. TODO: Fix this by using Buffers.
  216. try (InputStream in = f.openEntryStream()) {
  217. ObjectId id = inserter.insert(OBJ_BLOB, len, in);
  218. entry.setObjectId(id);
  219. }
  220. } else {
  221. entry.setLength(0);
  222. entry.setLastModified(Instant.ofEpochSecond(0));
  223. entry.setObjectId(f.getEntryObjectId());
  224. }
  225. builder.add(entry);
  226. lastAdded = path;
  227. }
  228. inserter.flush();
  229. builder.commit();
  230. setCallable(false);
  231. } catch (IOException e) {
  232. Throwable cause = e.getCause();
  233. if (cause != null && cause instanceof FilterFailedException)
  234. throw (FilterFailedException) cause;
  235. throw new JGitInternalException(
  236. JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
  237. } finally {
  238. if (dc != null)
  239. dc.unlock();
  240. }
  241. return dc;
  242. }
  243. /**
  244. * Set whether to only match against already tracked files
  245. *
  246. * @param update
  247. * If set to true, the command only matches {@code filepattern}
  248. * against already tracked files in the index rather than the
  249. * working tree. That means that it will never stage new files,
  250. * but that it will stage modified new contents of tracked files
  251. * and that it will remove files from the index if the
  252. * corresponding files in the working tree have been removed. In
  253. * contrast to the git command line a {@code filepattern} must
  254. * exist also if update is set to true as there is no concept of
  255. * a working directory here.
  256. * @return {@code this}
  257. */
  258. public AddCommand setUpdate(boolean update) {
  259. this.update = update;
  260. return this;
  261. }
  262. /**
  263. * Whether to only match against already tracked files
  264. *
  265. * @return whether to only match against already tracked files
  266. */
  267. public boolean isUpdate() {
  268. return update;
  269. }
  270. }