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