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