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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.util.Collection;
  49. import java.util.LinkedList;
  50. import org.eclipse.jgit.JGitText;
  51. import org.eclipse.jgit.api.errors.JGitInternalException;
  52. import org.eclipse.jgit.api.errors.NoFilepatternException;
  53. import org.eclipse.jgit.dircache.DirCache;
  54. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  55. import org.eclipse.jgit.dircache.DirCacheBuilder;
  56. import org.eclipse.jgit.dircache.DirCacheEntry;
  57. import org.eclipse.jgit.dircache.DirCacheIterator;
  58. import org.eclipse.jgit.lib.Constants;
  59. import org.eclipse.jgit.lib.FileMode;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectInserter;
  62. import org.eclipse.jgit.lib.Repository;
  63. import org.eclipse.jgit.treewalk.FileTreeIterator;
  64. import org.eclipse.jgit.treewalk.TreeWalk;
  65. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  66. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  67. /**
  68. * A class used to execute a {@code Add} command. It has setters for all
  69. * supported options and arguments of this command and a {@link #call()} method
  70. * to finally execute the command. Each instance of this class should only be
  71. * used for one invocation of the command (means: one call to {@link #call()})
  72. *
  73. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-add.html"
  74. * >Git documentation about Add</a>
  75. */
  76. public class AddCommand extends GitCommand<DirCache> {
  77. private Collection<String> filepatterns;
  78. private WorkingTreeIterator workingTreeIterator;
  79. private boolean update = false;
  80. /**
  81. *
  82. * @param repo
  83. */
  84. public AddCommand(Repository repo) {
  85. super(repo);
  86. filepatterns = new LinkedList<String>();
  87. }
  88. /**
  89. * @param filepattern
  90. * File to add content from. Also a leading directory name (e.g.
  91. * dir to add dir/file1 and dir/file2) can be given to add all
  92. * files in the directory, recursively. Fileglobs (e.g. *.c) are
  93. * not yet supported.
  94. * @return {@code this}
  95. */
  96. public AddCommand addFilepattern(String filepattern) {
  97. checkCallable();
  98. filepatterns.add(filepattern);
  99. return this;
  100. }
  101. /**
  102. * Allow clients to provide their own implementation of a FileTreeIterator
  103. * @param f
  104. * @return {@code this}
  105. */
  106. public AddCommand setWorkingTreeIterator(WorkingTreeIterator f) {
  107. workingTreeIterator = f;
  108. return this;
  109. }
  110. /**
  111. * Executes the {@code Add} command. Each instance of this class should only
  112. * be used for one invocation of the command. Don't call this method twice
  113. * on an instance.
  114. *
  115. * @return the DirCache after Add
  116. */
  117. public DirCache call() throws NoFilepatternException {
  118. if (filepatterns.isEmpty())
  119. throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
  120. checkCallable();
  121. DirCache dc = null;
  122. boolean addAll = false;
  123. if (filepatterns.contains("."))
  124. addAll = true;
  125. ObjectInserter inserter = repo.newObjectInserter();
  126. try {
  127. dc = repo.lockDirCache();
  128. DirCacheIterator c;
  129. DirCacheBuilder builder = dc.builder();
  130. final TreeWalk tw = new TreeWalk(repo);
  131. tw.addTree(new DirCacheBuildIterator(builder));
  132. if (workingTreeIterator == null)
  133. workingTreeIterator = new FileTreeIterator(repo);
  134. tw.addTree(workingTreeIterator);
  135. tw.setRecursive(true);
  136. if (!addAll)
  137. tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
  138. String lastAddedFile = null;
  139. while (tw.next()) {
  140. String path = tw.getPathString();
  141. WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
  142. if (tw.getTree(0, DirCacheIterator.class) == null &&
  143. f != null && f.isEntryIgnored()) {
  144. // file is not in index but is ignored, do nothing
  145. }
  146. // In case of an existing merge conflict the
  147. // DirCacheBuildIterator iterates over all stages of
  148. // this path, we however want to add only one
  149. // new DirCacheEntry per path.
  150. else if (!(path.equals(lastAddedFile))) {
  151. if (!(update && tw.getTree(0, DirCacheIterator.class) == null)) {
  152. c = tw.getTree(0, DirCacheIterator.class);
  153. if (f != null) { // the file exists
  154. long sz = f.getEntryLength();
  155. DirCacheEntry entry = new DirCacheEntry(path);
  156. if (c == null || c.getDirCacheEntry() == null
  157. || !c.getDirCacheEntry().isAssumeValid()) {
  158. FileMode mode = f.getIndexFileMode(c);
  159. entry.setFileMode(mode);
  160. if (FileMode.GITLINK != mode) {
  161. entry.setLength(sz);
  162. entry.setLastModified(f
  163. .getEntryLastModified());
  164. InputStream in = f.openEntryStream();
  165. try {
  166. entry.setObjectId(inserter.insert(
  167. Constants.OBJ_BLOB, sz, in));
  168. } finally {
  169. in.close();
  170. }
  171. builder.add(entry);
  172. lastAddedFile = path;
  173. } else {
  174. Repository subRepo = Git.open(
  175. new File(repo.getWorkTree(), path))
  176. .getRepository();
  177. ObjectId subRepoHead = subRepo
  178. .resolve(Constants.HEAD);
  179. if (subRepoHead != null) {
  180. entry.setObjectId(subRepoHead);
  181. builder.add(entry);
  182. lastAddedFile = path;
  183. }
  184. }
  185. } else {
  186. builder.add(c.getDirCacheEntry());
  187. }
  188. } else if (!update){
  189. builder.add(c.getDirCacheEntry());
  190. }
  191. }
  192. }
  193. }
  194. inserter.flush();
  195. builder.commit();
  196. setCallable(false);
  197. } catch (IOException e) {
  198. throw new JGitInternalException(
  199. JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
  200. } finally {
  201. inserter.release();
  202. if (dc != null)
  203. dc.unlock();
  204. }
  205. return dc;
  206. }
  207. /**
  208. * @param update
  209. * If set to true, the command only matches {@code filepattern}
  210. * against already tracked files in the index rather than the
  211. * working tree. That means that it will never stage new files,
  212. * but that it will stage modified new contents of tracked files
  213. * and that it will remove files from the index if the
  214. * corresponding files in the working tree have been removed.
  215. * In contrast to the git command line a {@code filepattern} must
  216. * exist also if update is set to true as there is no
  217. * concept of a working directory here.
  218. *
  219. * @return {@code this}
  220. */
  221. public AddCommand setUpdate(boolean update) {
  222. this.update = update;
  223. return this;
  224. }
  225. /**
  226. * @return is the parameter update is set
  227. */
  228. public boolean isUpdate() {
  229. return update;
  230. }
  231. }